使用Golang和Gorm获取完整对象,包括子对象

使用Golang和Gorm获取完整对象,包括子对象,go,go-gorm,Go,Go Gorm,我正在使用Gorm和Golang从我的数据库中获取数据。是否可以使Gorm同时获取对象子对象(外键) 数据库表 users +----+---------+------------+ | id | name | country_id | +----+---------+------------+ | 1 | Adam | 1 | | 2 | Bertil | 1 | | 3 | Charlie | 2 | +----+--

我正在使用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?
型号

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?
获取所有用户的代码

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",
        }
    },
    ...
]
期望的结果

[
    {
        "name": "Adam",
        "country" : {
            "name": "",
        }
    },
    ...
]
[
    {
        "name": "Adam",
        "country" : {
            "name": "Sweden",
        }
    },
    ...
]
非常感谢您的输入


/Klarre

是的,这是可能的,它被称为

users:=make([]用户,0)
DB.Preload(“国家”).Find(和用户)

谢谢!正是我想要的。:)