【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,
	}
]
相关推荐
无名之辈J7 小时前
系统崩溃(OOM)
后端
码农刚子7 小时前
ASP.NET Core Blazor简介和快速入门 二(组件基础)
javascript·后端
间彧7 小时前
Java ConcurrentHashMap如何合理指定初始容量
后端
深思慎考7 小时前
RabbitMQ 入门:基于 AMQP-CPP 的 C++ 实践指南与二次封装
开发语言·c++·分布式·rabbitmq·api
catchadmin7 小时前
PHP8.5 的新 URI 扩展
开发语言·后端·php
少妇的美梦7 小时前
Maven Profile 教程
后端·maven
白衣鸽子7 小时前
RPO 与 RTO:分布式系统容灾的双子星
后端·架构
Jagger_7 小时前
SOLID原则与设计模式关系详解
后端
似水流年 光阴已逝7 小时前
从Excel姓名匹配案例学Python:由点及面的系统化学习指南
开发语言·python·excel
间彧7 小时前
Java: HashMap底层源码实现详解
后端