Today I Learned

hashrocket A Hashrocket project

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()
See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.