前言
gorm中的Joins
方法只支持一对一关系。需要想要支持其它多关系表的查询,需要手写关联关系。只要记住下面的方式在看一下示例就很容易记住了:
- 一对一关系:只有一对一关系才能直接使用gorm原生的Joins来查询关联表的数据。
- 一对多、多对一关系: 要手写一层关联关系。
- 多对多关系:因为有一张关联表,所以需要手写两层关联关系。
示例
1. 一对一关系
project ---- costumer
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19func GetProjectList(info GetProjectRequest) (resp []Project, total int64, err error) { resp = []Project{} // 预加载关联字段 var db = DB().Model(&Project{}).Preload("Cosutmer") //添加关联表处查询条件 if info.CostumerName != "" { //等同于db = db.Joins("Costumer").Where(fmt.Sprintf(""Costumer".name like '%%%v%%'", info.CostumerName)) db = db.Joins("Costumer").Clauses(clause.Like{ Column: "Costumer.name", Value: "%" + info.CostumerName + "%", }) } //查询 db.Count(&total) err = db.Find(&resp).Error return )
2. 一对多关系
child ----* toy
复制代码
1
2
3
4
5
6
7
8
9
10
11
12func GetChildrenList(info GetChildrenListReq) (resp []Child, total int64, err error) { resp = []Child{} //加载关联字段 db := DB().Model(&Child{}).Preload("Toys") //添加关联表的查询条件 db.Joins("LEFT JOIN toy t1 ON t1.child_id = child.id").Where("t1.name = ?", "纸飞机") //数据查询 db.Count(&total) err = db.Find(&resp).Error return )
3. 多对一关系
toy *---- child
复制代码
1
2
3
4
5
6
7
8
9
10
11
12func GetToysList(info GetChildrenListReq) (resp []Toy, total int64, err error) { resp = []Toy{} //加载关联字段 db := DB().Model(&Toy{}).Preload("Child") //添加关联表的查询条件 db.Joins("LEFT JOIN child t1 ON t1.id = toy.child_id").Where("t1.child_name = ?", "刘涛").Find(&toys) //数据查询 db.Count(&total) err = db.Find(&resp).Error return )
4. 多对多关系
project *----* project_charge_persons_rel *----* ent_employee
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18func GetProjectList(info GetProjectRequest) (resp []Project, total int64, err error) { resp = []Project{} // 预加载关联字段 var db = DB().Model(&Project{}).Preload("ChargePersons") if info.BusinessPersonName != "" { // 加载多对多关系表 db = db.Joins("LEFT JOIN project_charge_persons_rel t1 ON project.id = t1.project_id"). //加载多对多关系的另一张表 Joins("LEFT JOIN ent_employee t2 ON t1.employee_id = t3.id AND t2.deleted_at IS NULL"). //添加关联表的查询条件 Where("t2.name like ?", "%"+info.BusinessName+"%") } //数据查询 db.Count(&total) err = db.Find(&resp).Error return )
另一种,把Where("t2.name like ?", "%"+info.BusinessName+"%")
换成下面这种方法,查询速度会提升一丢丢
复制代码
1
2
3
4
5
6Clauses(clause.Like{ Column: "t2.name", Value: "%" + info.BusinessName + "%", })
最后
以上就是无聊可乐最近收集整理的关于gorm使用Joins方法查询关联表数据的示例前言示例的全部内容,更多相关gorm使用Joins方法查询关联表数据内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复