Filter on many to many relationship
I want to find all sites where a user is a member in.
I have 3 tables that I have setup relations between
Now I am trying to figure out how to query all sites where user with a specific ID is a member in.
But when I do the following query, I just get all sites but with an empty array for the sites where the user is not a member in. My goal is to only get the sites where the user is a member in.
How can I query this?
3 Replies
Hi, @Tobias!
In the query, a
LEFT JOIN LATERAL
with a subquery is used to aggregate site member data into a JSON array. However, the condition linking the user to the sites is applied only within the subquery, not to the main selection of sites. This results in the query returning all sites but aggregates member data only for those sites where the specified user is a member. For sites where the user is not a member, an empty JSON array is returned.
I think you can do something like this in your case:
This query retrieves all sites where user with specific id is a member. In members
you always have only 1 user record due to specific id.Hi @solo , thank you for your reply. I figured it was a bit more complex than non working solution.
btw, you can use query builder for this case and it will be a bit easier