Skip to content
Advertisement

Polymorphic association query multiple JOIN as separate columns

I’m trying to extract a query that needs to access a polymorphic association table in SQL twice (I need to JOIN it on both ‘types’)

Here is the structure for the SQL tables.

I want to query each individual answer from the ‘Answer’ table, inner join with ‘User’ table on User.id == Answer.user_id, and inner join with ‘UserGroup’ table to get the ‘group_id’ for those with usergroupable_type == ‘User’ and usergroupable_id == User.id so that I can join to the ‘Group’ table to obtain the Group.name.

After that, I would like to obtain the AdminUser.name from the ‘AdminUser’ table by connecting with the polymorphic ‘UserGroup’ table on usergroupable_type == ‘AdminUser’.

Basically, I would like to obtain the Group.name, AdminUser.name per row in ‘Answer’ table.

Advertisement

Answer

If I understand right then something like

Should do it, but if I have misunderstood maybe share some sample data

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement