【发布时间】: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",
}
},
...
]
非常感谢您的意见!
/克拉雷
【问题讨论】: