简体   繁体   English

在golang的GORM中引用另一个元素

[英]Referencing another element in golang's GORM

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. 这与GORM的Related()函数完美配合。 However, I'd like to have Facebook-style structs returned, like this: 但是,我想返回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"
}

This can be done by adding a Client Client object to Item . 这可以通过将Client Client对象添加到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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM