【问题标题】:Retrieving many-to-many results from GORM从 GORM 检索多对多结果
【发布时间】:2018-05-31 16:59:40
【问题描述】:

我正在使用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"`
}

使用 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 会自动填充它。有没有我遗漏的步骤?

【问题讨论】:

    标签: mysql database go go-gorm


    【解决方案1】:

    查询服务前需要Preload资源字段:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-10
      • 2015-09-03
      • 2017-03-27
      • 1970-01-01
      • 2020-11-16
      • 2012-07-02
      • 1970-01-01
      • 2019-06-11
      相关资源
      最近更新 更多