【go】gorm\xorm\ent多表联查

文章目录

  • 1 gorm
  • 2 xorm
  • 3 ent

前言:本文介绍golang三种orm框架联表查询

1 gorm

type UserTest struct {
	Count     int     `json:"count,omitempty"`
	Type      string  `json:"type,omitempty"`
}
res := []UserTest{}
db.Joins("LEFT JOIN user ON order.user_id = user.id").Find(&res) 

2 xorm

err := db.Table("user").Select("name as org, count(status) as count").
	Join("LEFT", "order", "user.id= order.user_id").
	In("name", orgNames).
	GroupBy("name").
	OrderBy("count(status) desc").Find(&res)

3 ent

err := db.User.Query().
	Where(user.CompanyIDIn(companyIds...)).
	GroupBy(user.FieldCompanyID).
	Aggregate(
		func(s *sql.Selector) string {
			t := sql.Table(order.Table)
			s.Join(t).On(s.C(user.FieldID), t.C(order.FieldUserID))
			return sql.As(sql.Count(t.C(order.FieldBandwidth)), "count")
		},
	).Scan(c, &res)

输出:

[
	{
		"type": "xxx",
		"count": 24
	},
	{
		"type": "yyy",
		"count": 65,
	}
]

你可能感兴趣的:(go,golang,开发语言,后端)