从 GORM 中检索多对多结果

ksk*_*cou 2 mysql database go go-gorm

我正在使用gorm映射我的数据库。

我有两个具有多对多关系的表(serviceresource)。我在代码中对它们进行建模,如下所示:

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"`
}
Run Code Online (Sandbox Code Playgroud)

使用 gorm 的AutoMigrate创建以下表:

数据库图 m2m

(我还执行了一个原始 SQL 查询以在映射表中添加 id 主键。)

要创建新服务,我使用以下代码:

service := Service{
    Name: "core",
    Resources: []Resource{
        {Name: "ec2"},
        {Name: "dynamo"},
    },
}
db.Create(&service)
Run Code Online (Sandbox Code Playgroud)

这将创建所有资源以及服务service_resource,并按预期将它们之间的关系填充到表中。

但是,我的问题是当我查询服务时。我使用以下代码来检索所有服务:

services := []model.Service{}
db.Find(&services)
Run Code Online (Sandbox Code Playgroud)

这在填充了服务数组的情况下成功返回,但Resources每个服务的数组为空:

"services": [
    {
        "ID": 1,
        "Name": "core",
        "Resources": null
    },
    ...
]
Run Code Online (Sandbox Code Playgroud)

我假设 gorm 会自动填充它。有什么我遗漏的步骤吗?

ksk*_*cou 6

您需要在查询服务之前预加载资源字段:

services := []model.Service{}
db.Preload("Resources").Find(&services) // error checking ommited
Run Code Online (Sandbox Code Playgroud)

这正确填充了Resources每个服务的字段。