将 MySQL 查询转换为 GORM 模型查询
时间:2024-03-19
浏览:468
作者:佚名
**文章首段摘要:** 在使用 GORM 时,可以通过修改模型结构和存储库方法来关联数据并实现复杂查询。为了在返回的 JSON 响应中包含每个作业的作者信息,可以将作者字段添加到作业模型中。此外,需要在存储库方法中预加载用户关联以加载作者数据。通过这些修改,可以有效地从数据库中检索每个作业及其作者的信息。
问题内容
我有两个表:users 和 jobs,其中每个用户可以拥有多个作业,但一个特定作业属于一个用户。
type job struct {
id uint `gorm:"primarykey" json:"id"`
title string `gorm:"type:varchar(255); not null" json:"title"`
content string `gorm:"not null" json:"content"`
userid uint `json:"-"`
}
type user struct {
id uint `gorm:"primarykey" json:"-"`
uuid uuid.uuid `gorm:"type:char(36) not null" json:"-"`
name string `gorm:"type:varchar(255); not null" json:"name"`
jobs []job `json:"-"`
}
我想要每一篇文章及其作者。
以下查询有效:
select j.id, j.title, j.content, u.name as author from jobs as j inner join users as u on j.user_id = u.id
在戈尔姆:
func (jobrepo repository) findall() []entity.job {
var jobs []entity.job
jobrepo.db.find(&jobs)
// how do we handle the rest?
return jobs
}
我必须返回以下 json 响应:
job_id: <random_id>
job_title: "Test Title Content",
job_content: "Test Job Content",
author: {
name: "Test User Name"
}
如何获取每个帖子的作者数据?
解决方案
查看需要生成的 json 响应,您可以首先将 user 字段添加到 job 结构中,如下所示:
type job struct {
id uint `gorm:"primarykey" json:"id"`
title string `gorm:"type:varchar(255); not null" json:"title"`
content string `gorm:"not null" json:"content"`
userid uint `json:"-"`
user user `json:"author"`
}
此外,只需在您的存储库方法中进行一点小小的更改即可加载它。我添加了错误检查,因为您应该始终拥有它们。
func (jobRepo repository) FindAll() ([]entity.Job, error) {
var jobs []entity.Job
tx := jobRepo.db.Preload("User").Find(&jobs)
return jobs, tx.Error
}好了,本文到此结束,带大家了解了《将 MySQL 查询转换为 GORM 模型查询》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
12.01
12.01
热门专题
