我有一个包含项目和客户的数据库。每个项目可能属于一个客户。现在,我的结构是:
type Item struct {
Id int64
Barcode string `sql:"not null;unique"`
Name string
...
ClientId int64
CreatedAt time.Time
UpdatedAt time.Time
}
type Client struct {
Id int64
Name string
Telephone int64
}
这与 GORM 的 Related()
函数配合得很好。但是,我希望返回 Facebook 样式的结构,如下所示:
{
"Id": 1,
"Barcode": "AA4854845",
"Name": "100m 3.5mm",
"Model": "Random",
"Description": "test",
"Status": "new",
"BoxId": 0,
"Client": {
"Id": 3,
"Name": "John",
"Telephone": 123456789
},
"CreatedAt": "2014-06-05T16:59:35.639115765Z",
"UpdatedAt": "2014-06-05T16:59:35.639119134Z"
}
这可以通过将 Client Client
对象添加到 Item
来完成。但后来我得到了
"ClientId": 0,
"Client": {
"Id": 0,
...
},
这很讨厌。我是否遗漏了一些可以帮助我解决这个问题的东西?
最佳答案
您应该使用预加载功能,查看:https://github.com/jinzhu/gorm#preloading-eager-loading
关于database - 在 golang 的 GORM 中引用另一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24066146/