Work with Associations in Queries
Learn how to work with associations in queries.
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”
:
album = Repo.get_by(Album, title: "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 ...