Ecto Query preloading complex association

This is really good advice and is what I ended up doing.

So to help anyone who’s stuck with a similar problem, here is my less-heavyweight query(I only Ecto.preload :mediaitemartifacts at first).

    from(m in MediaItem,
      join: con in ContentMediaItems,
      on: m.id == con.media_item_id,
      where: is_nil(m.published_at) == false,
      join: chan in assoc(con, :channel),
      where: chan.id == con.channel_id,
      join: org in Org,
      on: m.org_id == org.id,
      where: org.slug == ^org_slug,
      order_by: [{:desc, :published_at}],
      preload: [:mediaitemartifacts],
      select: %{id: m.id, inserted_at: m.inserted_at, media_item: m, channel: chan}
    )

and later on, in the controller, I Repo.preload() the contents:

list =
    Enum.map(list, fn %{media_item: media_item, channel: channel} ->
        %{media_item: media_item, channel: Repo.preload(channel, :contents)}
    end)