Ecto: Preload with Joins to Save Database Trips
Today I learned that you can combine preload
with join
in Ecto to fetch related data in a single query instead of making multiple database trips.
For example, instead of doing this:
from(
u in User,
where: u.status == :active,
preload: [:emails]
) |> Repo.all()
Which runs 2 queries in db, you can do this in a single query:
from(
u in User,
join: e in assoc(u, :emails),
where: u.status == :active,
preload: [emails: e]
) |> Repo.all()
Tweet