在 Gorm (golang) 中使用指向外键相关模型的指针引用

假设您有如下数据库模型:


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 中获取,但国家在所有城市中变得相同。


Smart猫小萌
浏览 103回答 1
1回答

侃侃无极

也尝试将 countryId 作为指针。像这样 CountryId    *string   `json:"country_id"`实际上我试图用你的代码示例复制错误,但它运行良好。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go