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

文章目录

  • [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,
	}
]
相关推荐
寻寻觅觅☆9 分钟前
东华OJ-基础题-104-A == B ?(C++)
开发语言·c++
lightqjx19 分钟前
【C++】unordered系列的封装
开发语言·c++·stl·unordered系列
掘金者阿豪24 分钟前
关系数据库迁移的“暗礁”:金仓数据库如何规避数据完整性与一致性风险
后端
zh_xuan34 分钟前
kotlin lazy委托异常时执行流程
开发语言·kotlin
ServBay41 分钟前
一个下午,一台电脑,终结你 90% 的 Symfony 重复劳动
后端·php·symfony
sino爱学习1 小时前
高性能线程池实践:Dubbo EagerThreadPool 设计与应用
java·后端
阿猿收手吧!1 小时前
【C++】string_view:高效字符串处理指南
开发语言·c++
颜酱1 小时前
从二叉树到衍生结构:5种高频树结构原理+解析
javascript·后端·算法
掘金者阿豪1 小时前
UUID的隐形成本:一个让数据库“慢下来”的陷阱
后端
用户084465256371 小时前
Docker 部署 MongoDB Atlas 到服务端
后端