Selecting preload/virtual field

(adding to my answer from How to use array_agg in ecto to return structs)

If you want to fetch, say, 50 users along with all of their posts, you could write that:

users_query =
  from(u in User, limit: 50) # etc

result =
  users_query
  |> Repo.all()
  |> Repo.preload(:posts)
  |> Map.new(fn u -> {u.id, u.posts} end)

What you don’t want to do is waste the database’s CPU encoding things into JSON to try to squeeze this into one query.