Home  >  Article  >  Backend Development  >  GORM: How to link one to one?

GORM: How to link one to one?

WBOY
WBOYforward
2024-02-11 11:45:08778browse

GORM: How to link one to one?

GORM is a popular Go language ORM library used to simplify database operations. When using GORM for one-to-one linking, we can achieve this by defining the relationship between structures. First, we need to add a foreign key field to the structure, and then use GORM's `BelongsTo` method to associate the two structures. Next, we can use the `Preload` method to preload the related data at query time so that it can be fetched together when needed. In this way, we can easily implement one-to-one links and conveniently operate related data.

Question content

I am trying to load queue items from the database. I've created an API endpoint but am unable to get the data for the queue items to be preloaded. Instead, the entire "data" object is filled with null values.

Handler:

func QueueItemHandler(w http.ResponseWriter, r *http.Request) {
    var queueItems QueueItem
    var builder = database.Model(QueueItem{})

    var queryError = builder.
        Preload("Status").
        Preload("Data").
        Find(&queueItems).
        Error

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(queueItems)
}

Here's how my gorm model is set up:

type QueueItemStatus struct {
    ID          int64  `json:"id" gorm:"primary_key"`
    Name        string `json:"name"`
    Description string `json:"description"`
}

type QueueItemData struct {
    ID            int64  `json:"id" gorm:"primary_key"`
    QueueItemId   int64  `json:"queue_item_id"`
    ScreenshotUrl string `json:"screenshot_url"`
}

type QueueItem struct {
    ID            int64                  `json:"id" gorm:"primary_key"`
    SourceUrl     string                 `json:"source_url"`
    OriginId      int64                  `json:"origin_id"`
    StatusId      int64                  `json:"status_id"`
    Status        QueueItemStatus `json:"status"`
    Data          QueueItemData   `json:"data" gorm:"foreignKey:id,references:queue_item_id"`
    CreatedAt     time.Time              `json:"created_at"`
}

I'm thinking maybe I set up the model to point to the wrong column (if any)?

Solution

Try to change this

Data       QueueItemData    `json:"data" gorm:"foreignKey:QueueItemId;references:ID"`

The above is the detailed content of GORM: How to link one to one?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete