从 GORM 中检索多对多结果
Retrieving many-to-many results from GORM
我正在使用 gorm 映射我的数据库。
我有两个具有多对多关系的 table(service
和 resource
)。我在代码中对它们进行建模:
type Service struct {
BaseModel
Name string `gorm:"not null;unique_index"`
Resources []Resource `gorm:"many2many:service_resource"`
}
type Resource struct {
BaseModel
Name string `gorm:"not null;unique_index"`
}
使用 gorm 的 AutoMigrate 创建了以下 table:
(我还执行了原始 SQL 查询以在映射 table 中添加 id 主键。)
要创建新服务,我使用以下代码:
service := Service{
Name: "core",
Resources: []Resource{
{Name: "ec2"},
{Name: "dynamo"},
},
}
db.Create(&service)
这将创建所有资源以及服务,并在 service_resource
table 中填写它们之间的关系,正如预期的那样。
但是,我的问题是在查询服务时。我使用以下代码检索所有服务:
services := []model.Service{}
db.Find(&services)
此 returns 已成功填充服务数组,但每个服务的 Resources
数组为空:
"services": [
{
"ID": 1,
"Name": "core",
"Resources": null
},
...
]
我假设 gorm 会自动填充它。我是否缺少某些步骤?
在查询服务之前,您需要Preload资源字段:
services := []model.Service{}
db.Preload("Resources").Find(&services) // error checking ommited
这会正确填充每个服务的 Resources
字段。
我正在使用 gorm 映射我的数据库。
我有两个具有多对多关系的 table(service
和 resource
)。我在代码中对它们进行建模:
type Service struct {
BaseModel
Name string `gorm:"not null;unique_index"`
Resources []Resource `gorm:"many2many:service_resource"`
}
type Resource struct {
BaseModel
Name string `gorm:"not null;unique_index"`
}
使用 gorm 的 AutoMigrate 创建了以下 table:
(我还执行了原始 SQL 查询以在映射 table 中添加 id 主键。)
要创建新服务,我使用以下代码:
service := Service{
Name: "core",
Resources: []Resource{
{Name: "ec2"},
{Name: "dynamo"},
},
}
db.Create(&service)
这将创建所有资源以及服务,并在 service_resource
table 中填写它们之间的关系,正如预期的那样。
但是,我的问题是在查询服务时。我使用以下代码检索所有服务:
services := []model.Service{}
db.Find(&services)
此 returns 已成功填充服务数组,但每个服务的 Resources
数组为空:
"services": [
{
"ID": 1,
"Name": "core",
"Resources": null
},
...
]
我假设 gorm 会自动填充它。我是否缺少某些步骤?
在查询服务之前,您需要Preload资源字段:
services := []model.Service{}
db.Preload("Resources").Find(&services) // error checking ommited
这会正确填充每个服务的 Resources
字段。