I am learning how to compose queries using Ecto. I would like to filter results from a has_many through relationship, with one call to the database via Repo.all() if that is possible.
I assumed I could do this by composing this query using existing queries. e.g.
def users(organization_id) do
Repo.get(Organization, organization_id)
|> Ecto.assoc(:users)
end
def bookings(%{organization_id: organization_id}) do
Repo.get(Organization, organization_id)
|> Ecto.assoc(:bookings)
end
and then, reuse one of the above:
def bookings(%{organization_id: organization_id, user_id: user_id}) do
Repo.get(Organization, organization_id)
|> Ecto.assoc(:bookings)
|> where([u], u.user_id == ^user_id)
end
But this does does not filter results by a given user_id. How can it be done? What am I missing?
Schema Info:
- An Organization can have many Users.
- A User can have many Bookings.
- An Organization has many bookings through Users.