Gorm和具有嵌套结构和关系的元素切片

I am using gorm with MySQL driver.

I have following structs...

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
}

This is simple one-to-one relation (each City belongs to one State)

With raw SQL I extracted all cities into []City with this code:

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

How can I extract all the cities via gorm, so that gorm will scan inside of the each City.State field relevant State? Is there are any way to do what I need without calling Rows() and then manually Scan?

I expect something like:

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

But State is nil. What am I doing wrong?

You need to use the Preload method:

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

See more information in the Gorm doc: http://gorm.io/docs/preload.html