如何在 Jinzhu GORM 中创建 Left Join
How to create a Left Join in Jinzhu GORM
我无法在 jinzhu GORM(MySQL 数据库)中创建带左连接的简单查询
这些是我的结构:
type Prop struct {
ID uint
Status Status
StatusID uint
Name string
}
type Status struct {
ID uint
Name string
}
Prop 有一个指向 Status 的外键
我要执行的 SQL 查询是:
SELECT * from prop LEFT JOIN status ON prop.status_id = status.id
所以我将从道具 table 中检索所有记录,并加入状态 table
我试过了:
db.Find(&prop).Related(&status)
但没有成功。有人有什么建议吗?提前致谢
嘿@arthur_mastropietro,
我认为预加载 Prop
的相关 Status
是关键。尝试以下操作:
prop := Prop{}
if err := db.Model(&prop).Preload("Status").Find(&prop).Error; err != nil {
fmt.Println(err)
}
fmt.Printf("%+v\n", prop)
备注
您可以链接其他结构的预加载,即
Preload("Status").Preload("Something").
..等事实上,您可以链接大多数 Gorm
函数调用。
此外,如果 Status
也有另一个结构作为它的字段之一,您可以通过调用一次加载它们
Preload("Status.Something")
希望对您有所帮助!
我无法在 jinzhu GORM(MySQL 数据库)中创建带左连接的简单查询
这些是我的结构:
type Prop struct {
ID uint
Status Status
StatusID uint
Name string
}
type Status struct {
ID uint
Name string
}
Prop 有一个指向 Status 的外键
我要执行的 SQL 查询是:
SELECT * from prop LEFT JOIN status ON prop.status_id = status.id
所以我将从道具 table 中检索所有记录,并加入状态 table
我试过了:
db.Find(&prop).Related(&status)
但没有成功。有人有什么建议吗?提前致谢
嘿@arthur_mastropietro,
我认为预加载 Prop
的相关 Status
是关键。尝试以下操作:
prop := Prop{}
if err := db.Model(&prop).Preload("Status").Find(&prop).Error; err != nil {
fmt.Println(err)
}
fmt.Printf("%+v\n", prop)
备注
您可以链接其他结构的预加载,即
Preload("Status").Preload("Something").
..等事实上,您可以链接大多数 Gorm
函数调用。
此外,如果 Status
也有另一个结构作为它的字段之一,您可以通过调用一次加载它们
Preload("Status.Something")
希望对您有所帮助!