This github issue has an example of using a custom batch function to perform an aggregation.
The key is the %{batch: _, item: _} map passed to the dataloader helper, which I haven’t found documented anywhere except that issue ![]()
def run_batch(_, query, :post_count, users, repo_opts) do
user_ids = Enum.map(users, & &1.id)
default_count = 0
result =
query
|> where([p], p.user_id in ^user_ids)
|> group_by([p], p.user_id)
|> select([p], {p.user_id, count("*")})
|> Repo.all(repo_opts)
|> Map.new()
for %{id: id} <- users do
[Map.get(result, id, default_count)]
end
end
# Fallback to original run_batch
def run_batch(queryable, query, col, inputs, repo_opts) do
Dataloader.Ecto.run_batch(Repo, queryable, query, col, inputs, repo_opts)
end
Called from the GraphQL schema like:
field(:post_count, non_null(:integer) resolve dataloader(Posts, fn user, _args, _ ->
%{batch: {{:one, Post}, %{}}, item: [post_count: user]}
end)






















