Selecting fields in preloaded joins Ecto

This should make only one DB query.

post_query = 
  from p in Post,
    where: p.id == ^id,
    join: c in assoc(p, :comments),
    join: u in assoc(c, :user), 
    preload: [comments: {c, user: u}]

Regarding selecting association fields, you can do something like this (not tested)

post_query = 
  from p in Post,
    where: p.id == ^id,
    join: c in assoc(p, :comments),
    join: u in assoc(c, :user), 
    select: %{id: p.id, title: p.title, comments: p.comments, name: u.name}

Not sure exactly what you want to get back but that’s one way to select fields :slight_smile:

3 Likes