我有以下结构:
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:id;references:user_type_id" json:"user_type"`
LanguageID int64 `gorm:"column:language_id" json:"-"`
Language Language `gorm:"foreignKey:ID;references:LanguageID" json:"language"`
}
type BusinnesUserType struct {
ID int64 `gorm:"id" json:"id"`
Description json.RawMessage `gorm:"description" json:"description"`
}
type Language struct {
ID int64 `gorm:"id" json:"id"`
Description json.RawMessage `gorm:"description" json:"description"`
}
我正试着得到这样的东西:
{
"id":1,
"name":"dd",
"user_type":{
"id":1,
"description":{
"en":"admin"
}
},
"language":{
"id":1,
"description":{
"en":"English"
}
}
}
这是我用mysql:进行的gorm查询
db.Preload("UserType").Preload("Language").Where("id=?",1).Find(&user)
如果我使用Debug((选项,我会看到:
SELECT * FROM `languages` WHERE `languages`.`id` = 1
SELECT * FROM `business_user_types` WHERE `business_user_types`.`id` = 1
SELECT * FROM `users` WHERE `id` = 1
但我得到了以下json:
{
"id":1,
"name":"dd",
"user_type":{
"id":null,
"description":null
},
"language":{
"id":null,
"description":null
}
}
我使用预加载命令的方式不对?我已经尝试过Joins和Association,结果是一样的。
- 我认为用户模型应该是这样的
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"`
- 编辑您还必须手动ForeignKey
// 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>")
我已经找到了解决方案。问题出在";预加载";函数,因为需要与预加载的表的关系。现在,我的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"`
}