假設您有如下數據庫模型:package storagetype Country struct { ID string `json:"id" gorm:"type:uuid"` Name string `json:"name"` Code string `json:"code"`}type City struct { ID string `json:"id" gorm:"type:uuid"` Name string `json:"name"` Code *string `json:"code"` CountryId string `json:"country_id"` Country *Country `json:"country" gorm:"references:ID"` IATA *string `json:"iata"` Latitude *string `json:"latitude"` Longitude *string `json:"longitude"`}這個城市應該有一個指向國家模型的指針,以便更容易理解國家是否已經加入(在 sql 中)或沒有(例如if city.Country == nil {panic("for whatever reason")})當我嘗試獲取所有城市的列表時出現問題:package examplevar cities []storage.City tx.Joins("Country").Find(&cities)在這里,所有城市都很好地從 DB 中獲取,但國家在所有城市中變得相同。
1 回答

侃侃無極
TA貢獻2051條經驗 獲得超10個贊
也嘗試將 countryId 作為指針。
像這樣
CountryId *string `json:"country_id"`
實際上我試圖用你的代碼示例復制錯誤,但它運行良好。
- 1 回答
- 0 關注
- 98 瀏覽
添加回答
舉報
0/150
提交
取消