【发布时间】:2018-05-31 16:59:40
【问题描述】:
我正在使用gorm 映射我的数据库。
我有两个具有多对多关系的表(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 创建以下表:
(我还执行了一个原始 SQL 查询以在映射表中添加 id 主键。)
要创建新服务,我使用以下代码:
service := Service{
Name: "core",
Resources: []Resource{
{Name: "ec2"},
{Name: "dynamo"},
},
}
db.Create(&service)
这会随服务一起创建所有资源,并在service_resource 表中填写它们之间的关系,正如预期的那样。
但是,我的问题是在查询服务时。我使用以下代码检索所有服务:
services := []model.Service{}
db.Find(&services)
这会成功返回并填充服务数组,但每个服务的Resources 数组为空:
"services": [
{
"ID": 1,
"Name": "core",
"Resources": null
},
...
]
我假设 gorm 会自动填充它。有没有我遗漏的步骤?
【问题讨论】: