我可以用this case部分解决此问题

不幸的是,Preload()函数似乎无法在相关对象集中进一步深入研究。

为了澄清,我有以下模型:

    type Room struct {
        gorm.Model
        Name    string
        Games   []Game `gorm:"ForeignKey:RoomID"`
    }

    type Game struct {
        gorm.Model
        RoomID   int `gorm:"index"`
        Players  []Player `gorm:"ForeignKey:GameID"`
    }

    type Player struct {
        gorm.Model
        Name   string
        GameID int `gorm:"index"`
    }

当我使用创建的新Room,Game和Player对象创建新对象时,我得到以下数据返回(JSON编码):
    {"Value":{"ID":26,"CreatedAt":"2016-05-15T01:21:22.426234189-07:00","UpdatedAt":"2016-05-15T01:21:22.426234189-07:00","DeletedAt":null,"Name":"foo","Games":[{"ID":17,"CreatedAt":"2016-05-15T01:21:22.427026134-07:00","UpdatedAt":"2016-05-15T01:21:22.427026134-07:00","DeletedAt":null,"RoomID":26,"Turns":null,"Players":[{"ID":4,"CreatedAt":"2016-05-15T01:21:22.427560561-07:00","UpdatedAt":"2016-05-15T01:21:22.427560561-07:00","DeletedAt":null,"Name":"TestPlayer","GameID":17}],"Counter":1,"Assigned":false}],"Testing":false},"Error":null,"RowsAffected":1}

但是,如果我尝试使用preload()函数查询结构,则会得到以下信息:
    {"Value":{"ID":26,"CreatedAt":"2016-05-15T01:21:22.426234189-07:00","UpdatedAt":"2016-05-15T01:21:22.426234189-07:00","DeletedAt":null,"Name":"foo","Games":[{"ID":17,"CreatedAt":"2016-05-15T01:21:22.427026134-07:00","UpdatedAt":"2016-05-15T01:21:22.427026134-07:00","DeletedAt":null,"RoomID":26,"Turns":null,"Players":null,"Counter":1,"Assigned":false}],"Testing":false},"Error":null,"RowsAffected":1}

请注意,“播放器”部分现在为空。这是我的房间注册和房间查询功能:
    func RegisterRoom(w http.ResponseWriter, r *http.Request) {
        err := r.ParseForm()

        if err != nil {
            // Handle error
        }
        // r.PostForm is a map of our POST form values
        room := Room{
            Name: r.PostFormValue("label"),
            Games: []Game{{
                Counter: 1,
                Players: []Player{{Name: r.PostFormValue("username")}},
            }},
        }
        t := db.Create(&room)
        if err := json.NewEncoder(w).Encode(t); err != nil {
            panic(err)
        }
    }

func RoomShow(w http.ResponseWriter, r *http.Request) {
    var rm Room
    vars := mux.Vars(r)
    roomId := vars["roomId"]
    id, _ := strconv.Atoi(roomId)
    room := db.Preload("Games").First(&rm, id)
    result := db.Find(&room)
    json.NewEncoder(w).Encode(result)
}

最佳答案

解决了!答案在Nested Preloading额头下

10-04 10:13