Gorm复杂查询的返回值

huangapple go评论103阅读模式
英文:

Return value of Gorm complex query

问题

假设我有以下代码:

  1. type A struct {
  2. ID string `gorm:"primary_key"`
  3. Name string
  4. }
  5. type B struct {
  6. ID string `gorm:"primary_key"`
  7. AId string
  8. A A `gorm:"foreignkey:AId"`
  9. Val string
  10. }

如果我想在 A 或 B 上执行普通查询,我可以期望返回 A 或 B 结构体。但是如果我想进行联接查询,我应该期望在 Go 中返回哪个结构体?

例如,如果我的查询是:

  1. select * from a join b on a.id = b.a_id;

GORM 会返回什么样的结构体?

英文:

Let's say I have:

  1. type A struct {
  2. ID string `gorm:"primary_key"`
  3. Name string
  4. }
  5. type B struct {
  6. ID string `gorm:"primary_key"`
  7. AId string
  8. A A `gorm:"foreignkey:AId"`
  9. Val string
  10. }

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:

  1. select * from a join b on a.id = b.a_id;

What does GORM return as a struct?

答案1

得分: 1

将查询语句转换为gorm代码如下:

  1. 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结构体,用于存储表ab的所有字段。

  1. result := []struct {
  2. ID string `db:"aid"`
  3. Name string `db:"aname"`
  4. BId string `db:"bid"`
  5. AId string `db:"baid"`
  6. Val string `db:"bval"`
  7. }{}

然后,根据需要重新组织这个结果结构体,或者将该结构体返回给客户端使用。

英文:

Converting the query

  1. select * from a join b on a.id = b.a_id;

into gorm:

  1. 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.

  1. result := []struct {
  2. ID string `db:"aid"`
  3. Name string `db:"aname"`
  4. BId string `db:"bid"`
  5. AId string `db:"baid"`
  6. Val string `db:"bval"`
  7. }{}

Then, repackage this result struct as needed, or return this struct for the client to use.

huangapple
  • 本文由 发表于 2022年7月14日 03:02:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/72971372.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定