Search code examples
gouniongrails-orm

Golang gorm union function for orm approach


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?


Solution

  • 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