Join tables connected through join through

I have 3 tables.

This is just simple representation of relations.

 User (many to many :roles  join through :user_roles)
 Role (many to many :users join through :user_roles)
 Role(belongs_to :prof)

I want to filter out users where prof meets specific condition.

But I am confused about how to join these three . The confusion is how i combine the user and role table.

What you are looking for is this:

This will not fully solve the @leaf problem, as it in many-to-many relation when you want to filter out specific relation it will not be so easy. Simplest solution would be if Ecto would support existential queries directly which would greatly simplify this query. Instead we need to write something like:

filtered_user_ids =
  from role in Roles,
    inner_join: ur in "user_roles", on: == ur.role_id,
    group_by: ur.user_id,
    having: ^requested_prof_id not in fragment("array_agg(?)", role.prof_id),
    select: %{user_id: ur.user_id}

from user in User,
  inner_join: ur in subquery(^filtered_user_ids), on: == ur.user_id

I haven’t tested that query though, so it can have some issues.

If you want to use existential queries anyway then you can do:

from user in User,
  where: fragment("""
      SELECT 1
      FROM user_roles
      INNER JOIN roles
        ON = user_roles.role_id
      WHERE roles.prof_id = ?
        AND user_roles.user_id = ?

This seems to be working for me:

    |> join(
    user_roles in UserRoles, on: user_roles.user_id ==
  |> join(
    [u, user_roles],
    roles in Role, on: user_roles.role_id ==
  |> join(
    [u, user_roles, roles],
    prof in Prof, on: role.prof_id == and in ^prof_ids