【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,
	}
]
相关推荐
喜欢流萤吖~1 天前
微服务架构解析:从单体到分布式
spring boot·后端
小江的记录本1 天前
【分布式】分布式核心组件——分布式锁:Redis/ZooKeeper/etcd 实现方案(附全方位对比表)、优缺点、Redlock、时钟回拨问题
java·网络·redis·分布式·后端·zookeeper·架构
小江的记录本1 天前
【分布式】分布式核心组件——分布式ID生成:雪花算法、号段模式、美团Leaf、百度UidGenerator、时钟回拨解决方案
分布式·后端·算法·缓存·性能优化·架构·系统架构
晔子yy1 天前
【JAVA探索之路】从头开始讲透、实现单例模式
java·开发语言·单例模式
阿正的梦工坊1 天前
JavaScript 微任务与宏任务完全指南
开发语言·javascript·ecmascript
GetcharZp1 天前
拒绝低效!这款神器,让你的终端效率起飞 | 深度解析 fzf 终极指南
后端
知行合一。。。1 天前
Python--05--面向对象(属性,方法)
android·开发语言·python
青梅橘子皮1 天前
C语言---指针的应用以及一些面试题
c语言·开发语言·算法
自珍JAVA1 天前
高效处理Long列表与集合运算:基于RoaringBitmap的工具类解析与应用场景
后端
小码哥_常1 天前
Spring Boot项目上线秘籍:日志、监控、异常处理全攻略
后端