You cannot make the join table conditional, so in this case you will need to join the events for both users and organizations and use a joint join to combine common fields (for example, name) together.
select e.id, coalesce(u.name, o.name) owner_name from events e left join users u on e.owner_id = u.id and e.owner_type = 'user' left join organisations o on e.owner_id = o.id and e.owner_type = 'org'
However, you might consider creating an owner table that contains both users and organizations, with a structure like (id, type, org_id, name, ...). This will require only one connection, but may complicate other areas of your circuit, for example. user membership in the organization.
An alternative method would be to combine the joins of user and organization tables, and then to join the events once.
source share