英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论