Golang gorm的union函数用于ORM方法的实现。

huangapple go评论79阅读模式
英文:

Golang gorm union function for orm approach

问题

我正在尝试将两个结果合并在一起,我可以使用以下SQL查询语句:

SELECT id, created_at, updated_at, deleted_at, user_id, friend_id 
FROM public.friendlists where user_id = $1
union all 
SELECT id, created_at, updated_at, deleted_at, user_id, friend_id
FROM public.friendlists where friend_id = $1

我知道我可以直接使用SQL语句或者将两个结果连接起来。我只是想找出一种方法,因为我很好奇如何处理这个问题,并避免硬编码的SQL语句。
以下是我目前的代码:

db.Where(&models.Friendlist{UserId: userID}).
Or(&models.Friendlist{FriendId: userID}).
Order("created_at desc").
Find(&result)

我该如何在gorm中使用ORM方法来实现这个功能?或者这种方法是否可行?

英文:

I am trying to union two results with each other the sql-query I could use for would look like this:

SELECT id, created_at, updated_at, deleted_at, user_id, friend_id 
FROM public.friendlists where user_id = $1
union all 
SELECT id, created_at, updated_at, deleted_at, user_id, friend_id
FROM public.friendlists where friend_id = $1

I know I could just use the sql statement or just join the two results. I just want to find out a way because im curious how to handle this and to avoid hardcoded sql statements.
The following code is what I have so far:

db.Where(&models.Friendlist{UserId: userID}).
Or(&models.Friendlist{FriendId: userID}).
Order("created_at desc").
Find(&result)

How I could I do this with an ORM approach in gorm? Or is it even possible?

答案1

得分: 0

我不认为 GORM 中实现了 UNION 操作。

但是你可以使用原始查询和通过这个方法将结果转换为所需的结构 - https://gorm.io/docs/sql_builder.html#Raw-SQL

英文:

i don't think union is implemented in gorm.

but you can execute raw query with union and marshal result into structure required via this method - https://gorm.io/docs/sql_builder.html#Raw-SQL

huangapple
  • 本文由 发表于 2021年9月13日 04:04:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/69154831.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定