Gorm复杂查询的返回值

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

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

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.

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:

确定