【问题标题】:Fetch complete objects including children using Golang and Gorm使用 Golang 和 Gorm 获取包括孩子在内的完整对象
【发布时间】:2021-04-14 12:48:36
【问题描述】:

我正在使用 Gorm 和 Golang 从我的数据库中获取数据。是否可以让 Gorm 也获取对象子对象(外键)?

数据库表

users
+----+---------+------------+
| id | name    | country_id |
+----+---------+------------+
|  1 | Adam    |          1 |
|  2 | Bertil  |          1 |
|  3 | Charlie |          2 |
+----+---------+------------+

countries
+----+--------+
| id | name   |
+----+--------+
|  1 | Sweden |
|  2 | Norway |
+----+--------+

模型

type User struct {
    Id        int64   `json:"-"`
    Name      string  `json:"name"`
    CountryId int64   `json:"-"`
    Country   Country `json:"country"`
}

type Country struct {
    Id   int64  `json:"-"`
    Name string `json:"name"`
}

获取所有用户的代码

var users []User
DB.Find(&users) // Question: How should this be modified to automatically fetch the Country?

实际结果

[
    {
        "name": "Adam",
        "country" : {
            "name": "",
        }
    },
    ...
]

想要的结果

[
    {
        "name": "Adam",
        "country" : {
            "name": "Sweden",
        }
    },
    ...
]

非常感谢您的意见!

/克拉雷

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    是的,有可能,它叫做Preloading

    users := make([]User,0)
    DB.Preload("Country").Find(&users) 
    

    【讨论】:

    • 谢谢!正是我想要的。 :)
    猜你喜欢
    • 2014-12-21
    • 1970-01-01
    • 2018-11-09
    • 2018-12-14
    • 2018-08-10
    • 2014-03-08
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多