【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,
	}
]
相关推荐
陈随易8 小时前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·后端·程序员
IT_陈寒10 小时前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
子兮曰11 小时前
Agency-Agents 深度解析:400+ AI 专家的"梦之队"如何重塑开发工作流
前端·后端·vibecoding
用户83562907805112 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
小满zs12 小时前
Go语言第二章(小无相功)
后端·go
用户83562907805112 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
karry_k12 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
妙码生花12 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go
贰先生12 小时前
Xiuno BBS X版 用户封禁系统
后端
karry_k12 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端