Ecto query that accepts a list of structs

This ecto query accepts a user struct. How do I modify this so it accepts a list and returns the count

def count_invites(%User{id: user_id}) do
  from(r in Invitations,
    join: rt in assoc(r, :invite_token),
    join: i in assoc(r, :invitee),
    where: rt.user_id == ^user_id
  )
  |> Repo.aggregate(:count, :id)
end

I’m currently looping through the function, but seems inefficient.

Im not an ecto expert, but mapping over the list to get a list of IDs, then using in in the :where clause while calling Repo.all, shouldn’t that be enough?

I think this should work

user_ids = users |> Enum.map(& &1.id)
def count_invites(user_ids) do
  from(r in Invitations,
    join: rt in assoc(r, :invite_token),
    join: i in assoc(r, :invitee),
    where: rt.user_id in ^user_ids
  )
  |> Repo.aggregate(:count)
end

https://hexdocs.pm/ecto/Ecto.Query.API.html#in/2

2 Likes