2 回答
TA贡献1806条经验 获得超5个赞
我认为用户模型应该看起来像这样..
type Users struct {
ID int64 `gorm:"id" json:"id"`
Name int64 `gorm:"name" json:"name"`
UserTypeID int `gorm:"column:user_type_id" json:"-"`
UserType BusinnesUserType `gorm:"foreignKey:UserTypeID;" json:"user_type"` // changed this line
LanguageID int64 `gorm:"column:language_id" json:"-"`
Language Language `gorm:"foreignKey:LanguageID;" json:"language"` // changed this line
}
更改了此行..
Language Language `gorm:"foreignKey:LanguageID;" json:"language"`
UserType BusinnesUserType `gorm:"foreignKey:UserTypeID;" json:"user_type"`
编辑你必须手动外键
// User : Relations
DB.Model(&models.Users{}).AddForeignKey("user_type_id", "Businnesusertypes(id)", "<CASCADE/RESTRICT>", "<CASCADE/RESTRICT>")
DB.Model(&models.Users{}).AddForeignKey("language_id", "languages(id)", "<CASCADE/RESTRICT>", "<CASCADE/RESTRICT>")
TA贡献1784条经验 获得超8个赞
我已经找到了解决方案。问题出在“预加载”函数中,因为需要与预加载表的关系。现在,我的 gorm 查询是这样的:
result := db.Preload("UserType", "id=?", &user.UserTypeID).
Preload("Language", "id=?", &user.LanguageID).
Where("business_users.id=?", 1).Find(&user)
我的结构是这样的:
type BusinessUsers struct {
gorm.Model
Name string `gorm:"name" json:"name"`
UserTypeID int64
UserType BusinessUserType `gorm:"foreignkey:UserTypeID"`
LanguageID int64
Language Language `gorm:"foreignkey:LanguageID"`
}
- 2 回答
- 0 关注
- 80 浏览
添加回答
举报