文章目录
- [1 gorm](#1 gorm)
- [2 xorm](#2 xorm)
- [3 ent](#3 ent)
前言:本文介绍golang三种orm框架联表查询
1 gorm
go
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
go
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
go
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)
输出:
json
[
{
"type": "xxx",
"count": 24
},
{
"type": "yyy",
"count": 65,
}
]