I have a database that contains items and clients. Each item may belong to a single client. Right now, my structs are:
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
}
This works wonderfully with GORM's Related()
function. However, I'd like to have Facebook-style structs returned, like this:
{
"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"
}
This can be done by adding a Client Client
object to Item
. But then I end up with
"ClientId": 0,
"Client": {
"Id": 0,
...
},
which is nasty. Am I missing something that would help me solve this?
您应该使用预加载功能,并进行检查: https : //github.com/jinzhu/gorm#preloading-eager-loading
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.