gpt4 book ai didi

sqlite - 在 Go GORM 中显示 Foreign Keys 的 Foreign Keys

转载 作者:数据小太阳 更新时间:2023-10-29 03:27:13 26 4
gpt4 key购买 nike

我可以通过 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"`
}

当我使用创建的新房间、游戏和玩家对象创建新对象时,我得到以下返回数据(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}

请注意,Players 部分现在为空。这是我的房间注册和房间查询功能:

    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拍额头

关于sqlite - 在 Go GORM 中显示 Foreign Keys 的 Foreign Keys,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37236071/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com