gorm使用Joins方法查询关联表数据的示例

前言

gorm中的Joins方法只支持一对一关系。需要想要支持其它多关系表的查询,需要手写关联关系。只要记住下面的方式在看一下示例就很容易记住了:

  • 一对一关系:只有一对一关系才能直接使用gorm原生的Joins来查询关联表的数据。
  • 一对多多对一关系: 要手写一层关联关系。
  • 多对多关系:因为有一张关联表,所以需要手写两层关联关系。

示例

1. 一对一关系

project ---- costumer

func 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

func 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

func 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

func 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+"%")换成下面这种方法,查询速度会提升一丢丢

Clauses(clause.Like{
	Column: "t2.name",
	Value:  "%" + info.BusinessName + "%",
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值