【问题标题】:Gorm and slice of elements with nested structs and relations具有嵌套结构和关系的 Gorm 和元素切片
【发布时间】:2018-02-02 23:24:24
【问题描述】:

我正在使用 gormMySQL driver

我有以下结构...

type City struct {
    ID uint
    Name string
    Slug string
    StateID uint // foreign key, must be used like INNER JOIN state ON city.state_id = state.id
    State *State
}

type State struct {
    ID uint
    Name string
    Slug string
}

这是简单的一对一关系(每个城市属于一个州)

使用原始 SQL,我使用以下代码将所有城市提取到 []City

rows, err := db.Query(`SELECT c.id, c.name, c.slug, s.id, s.name, s.slug FROM city c INNER JOIN state s ON c.state_id = s.id`)
if err != nil {
    return err
}
defer rows.Close()

for rows.Next() {
    city := &City{
        State: &State{},
    }
    err = rows.Scan(&c.ID, &c.Name, &c.Slug, &c.State.ID, &c.State.Name, &c.State.Slug)
    if err != nil {
        return err
    }

    *c = append(*c, city)
}

return nil

如何通过 gorm 提取所有城市,以便 gorm 扫描每个 City.State 字段相关状态的内部?有什么方法可以在不调用Rows() 然后手动Scan 的情况下做我需要的事情吗?

我希望是这样的:

cities := make([]City, 0)
db.Joins(`INNER JOIN state ON state.id = city.state_id`).Find(&cities)

但是Statenil。我做错了什么?

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    你需要使用Preload方法:

    db.Preload("state").Joins("INNER JOIN state ON state.id = city.state_id").Find(&cities)

    在 Gorm 文档中查看更多信息:http://gorm.io/docs/preload.html

    【讨论】:

      猜你喜欢
      • 2016-02-22
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多