亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Gorm (golang) 中使用指向外鍵相關模型的指針引用

在 Gorm (golang) 中使用指向外鍵相關模型的指針引用

Go
Smart貓小萌 2022-12-19 21:07:57
假設您有如下數據庫模型: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"`

實際上我試圖用你的代碼示例復制錯誤,但它運行良好。


查看完整回答
反對 回復 2022-12-19
  • 1 回答
  • 0 關注
  • 98 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號