Work with Associations in Queries
Explore how to handle associations in Ecto queries to avoid performance issues caused by lazy loading. Understand Ecto's approach to preloading related records and how to use join and preload together to efficiently load nested data. This lesson helps you write clear and optimized database queries when working with Elixir structs and relational data.
We'll cover the following...
Now that we’ve got some associations defined, let’s put them to work. Go to the music_db project and open up a mix session with iex -S mix. First, grab the record for the album “Kind Of Blue”:
Let’s run it in the following terminal:
Our gut tells us that if we want to see the tracks for this album, we’ll do this:
album.tracks
However, this will not achieve the results we want. Instead, we get this:
This is not an error. It’s a placeholder value indicating that this album’s track records have not yet been retrieved from the database.
Lazy loading
We might well wonder why Ecto doesn’t just load the records for us when we ask for them, like some other database libraries do. This is a feature called lazy loading. The library checks to see if the ...