我正在使用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 . 我究竟做错了什么?