英文:
Return value of Gorm complex query
问题
假设我有以下代码:
type A struct {
ID string `gorm:"primary_key"`
Name string
}
type B struct {
ID string `gorm:"primary_key"`
AId string
A A `gorm:"foreignkey:AId"`
Val string
}
如果我想在 A 或 B 上执行普通查询,我可以期望返回 A 或 B 结构体。但是如果我想进行联接查询,我应该期望在 Go 中返回哪个结构体?
例如,如果我的查询是:
select * from a join b on a.id = b.a_id;
GORM 会返回什么样的结构体?
英文:
Let's say I have:
type A struct {
ID string `gorm:"primary_key"`
Name string
}
type B struct {
ID string `gorm:"primary_key"`
AId string
A A `gorm:"foreignkey:AId"`
Val string
}
If I wanted to do a normal query on A or B, I can just expect the A or B struct back. But if I wanted to do a join, what struct should I expect in go?
For example if my query were:
select * from a join b on a.id = b.a_id;
What does GORM return as a struct?
答案1
得分: 1
将查询语句转换为gorm代码如下:
db.Table("a").Select("a.id as aid, a.name as aname, b.id as bid, b.a_id as baid, b.val as bval").Joins("JOIN b ON a.id = b.a_id").Find(&result)
我们可以创建一个临时的result
结构体,用于存储表a
和b
的所有字段。
result := []struct {
ID string `db:"aid"`
Name string `db:"aname"`
BId string `db:"bid"`
AId string `db:"baid"`
Val string `db:"bval"`
}{}
然后,根据需要重新组织这个结果结构体,或者将该结构体返回给客户端使用。
英文:
Converting the query
select * from a join b on a.id = b.a_id;
into gorm:
db.Tables("a").Select("a.id as aid, a.name as aname, b.id as bid, b.a_id as baid, b.val as bval").Joins("JOIN b ON a.id = b.a_id").Find(&result)
We can just create a temporary result
struct that houses all fields from both tables a
and b
.
result := []struct {
ID string `db:"aid"`
Name string `db:"aname"`
BId string `db:"bid"`
AId string `db:"baid"`
Val string `db:"bval"`
}{}
Then, repackage this result struct as needed, or return this struct for the client to use.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论