
gorm中查询关联数据
在本文中,我们将探讨如何使用gorm查询包含多对多关联的模型。让我们考虑以下模型关系:
模型定义:
type table1 struct {
id string `gorm:"primary_key"`
table2s []*table2 //has many
}
type table2 struct {
id string `gorm:"primary_key"`
table1id string
table3s []*table3 `gorm:"many2many:table2_table3"` //many2many
}
type table3 struct {
id string `gorm:"primary_key"`
}查询示例:
现在,假设我们有一个表1的实例,其id为"id-1",并且我们希望获取与该表1关联的所有表3数据。
期望的结果:
table1:{
id: "id-1",
table2s:[
{
id: "table2-1",
table3s:[
{id: "table3-1"},
{id: "table3-2"},
...
]
},
...
]
}gorm查询:
要执行此查询,我们可以使用以下gorm代码:
var data []Table1
db.Preload("Table2").Preload("Table2.Table3").Find(&data)解释:
- db.preload("table2"):此行预加载了表1的table2关联。
- db.preload("table2.table3"):此行预加载了表2的table3关联。
- find(&data):此行查找所有表1的实例并填充预加载的关联。
执行此查询后,data变量将包含我们期望的结果,其中包含从表1开始,通过表2,关联到所有表3数据。










