I have a model like this
我有一个这样的模型
type User struct {
ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;default:gen_random_uuid()"`
Name string `json:"name" gorm:"unique"`
Jobs []JobUser `json:"jobs" gorm:"foreignKey:UserID;default:null"`
}
The model between User and Jobs looks like this
User和Jobs之间的模型如下所示
type JobUser struct {
ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;default:gen_random_uuid()"`
JobID uuid.UUID `json:"job_id"`
UserID uuid.UUID `json:"user_id"`
}
and lastly, this is what the job model looks like
最后,这是工作模式的样子
type Job struct {
ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;default:gen_random_uuid()"`
Name string `json:"name" gorm:"unique"`
Users []JobUser `json:"-" gorm:"foreignKey:JobID"`
}
im trying to query the contents of jobs from user, the response struct type should look like this
我正在尝试从User查询作业的内容,响应结构类型应该如下所示
type User struct {
ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;default:gen_random_uuid()"`
Name string `json:"name" gorm:"unique"`
Jobs []Job `json:"jobs"`
}
this is how i do it with gorm
我就是这么对待戈姆的
if err := db.DB.Preload("Jobs").Find(&roles).Error; err != nil {
return
}
but then this returns User with the model inbetween, which is not what i want
但这会返回带有中间模型的用户,这不是我想要的
how can i return User with Job model directly?
如何直接返回具有作业模型的用户?
更多回答
优秀答案推荐
If you want to return User
with Job
model directly without the JobUser
, you should use the gorm preload function with a custom query, something like this;
如果您希望在不使用JobUser的情况下直接返回具有作业模型的用户,则应将GORM预加载函数与自定义查询一起使用,如下所示;
var users []User
if err := db.DB.Preload("Jobs").Find(&users).Error; err != nil {
return err
}
更多回答
我是一名优秀的程序员,十分优秀!