使用 Golang 和 Gorm 获取完整的 objects 包括 children
Fetch complete objects including children using Golang and Gorm
我正在使用 Gorm 和 Golang 从我的数据库中获取数据。是否可以让 Gorm 也获取 objects children(外键)?
数据库表
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",
}
},
...
]
非常感谢您的输入!
/克拉尔
是的,这是可能的,它被称为Preloading。
users := make([]User,0)
DB.Preload("Country").Find(&users)
我正在使用 Gorm 和 Golang 从我的数据库中获取数据。是否可以让 Gorm 也获取 objects children(外键)?
数据库表
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",
}
},
...
]
非常感谢您的输入!
/克拉尔
是的,这是可能的,它被称为Preloading。
users := make([]User,0)
DB.Preload("Country").Find(&users)