假设您有如下数据库模型: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 关注
- 102 浏览
添加回答
举报
0/150
提交
取消