假设您有如下数据库模型:
package storage
type 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 example
var cities []storage.City
tx.Joins("Country").Find(&cities)
在这里,所有城市都很好地从 DB 中获取,但国家在所有城市中变得相同。
侃侃无极
相关分类