英文:
Retrieving many-to-many results from GORM
问题
我正在使用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 := Service{
Name: "core",
Resources: []Resource{
{Name: "ec2"},
{Name: "dynamo"},
},
}
db.Create(&service)
这将创建所有的资源,并且在service_resource
表中填充它们之间的关系,一切都正常,符合预期。
然而,我的问题是当我查询services时。我使用以下代码检索所有的services:
services := []model.Service{}
db.Find(&services)
这个查询成功返回了填充了services数组的结果,但是每个service的Resources
数组为空:
"services": [
{
"ID": 1,
"Name": "core",
"Resources": null
},
...
]
我原本以为gorm会自动填充它。我是否漏掉了某个步骤?
英文:
I am mapping my database using gorm.
I have two tables (service
and resource
) with a many-to-many relationship. I am modelling them in code as such:
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"`
}
Using gorm's AutoMigrate the following tables are created:
(I also executed a raw SQL query to add the id primary key in the mapping table.)
To create a new service, I use the following code:
service := Service{
Name: "core",
Resources: []Resource{
{Name: "ec2"},
{Name: "dynamo"},
},
}
db.Create(&service)
This creates all the resources along with the service and fills in the relationship between them in the service_resource
table just fine, as expected.
However, my problem is when I'm querying for the services. I use the following code to retrieve all services:
services := []model.Service{}
db.Find(&services)
This returns successfully with the services array populated, but the Resources
array of each service is empty:
"services": [
{
"ID": 1,
"Name": "core",
"Resources": null
},
...
]
I was under the assumption that gorm would populate it automatically. Is there some step that I'm missing?
答案1
得分: 7
你需要在查询服务之前预加载资源字段:
services := []model.Service{}
db.Preload("Resources").Find(&services) // 省略了错误检查
这样可以正确填充每个服务的`Resources`字段。
英文:
You need to Preload the resources field before querying for services:
services := []model.Service{}
db.Preload("Resources").Find(&services) // error checking ommited
This correctly populates the Resources
field of every service.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论