Playing Next Lesson In
seconds

Let's Learn AdonisJS 6 #5.2

Querying Relationships and Eager Vs Lazy Loading

In This Lesson

We'll learn how we can query our relationships using our Lucid Models. We'll then learn what the difference is between eagerly loading a relationship (load) and lazily loading a relationship (preload).

Created by
@tomgobich
Published

Join the Discussion 4 comments

Create a free account to join in on the discussion
  1. is there a risk of an n+1 issue when using lazy loading? ( first comment btw :) )

    1
    1. Responding to laariane-amine
      @tomgobich

      Hi laariane, great question!! Yes, n+1 is still possible, though unlike with other ORMs that offer auto lazy loading by reference since the loading is explicit with Lucid the n+1 issue becomes a little easier to spot.

      For example, here's a n+1 query using Lucid's lazy loading

      const movies = await Movie.all()
      
      for (let movie of movies) {
        // will loop through each movie and 
        // individually query each movie's director
        await movie.load('director')
      }
      Copied!

      This n+1 can be solved by switching to preloading or querying a list of directors rather than individually loading.

      const movies = await Movie
        .query() // still queries all movies since we aren't filtering at all
        .preload('director') // loads director info without n+1
      Copied!
      1
      1. Responding to tomgobich

        thanks for the reply, wouldn't it be better to use "preload" every time in this case to avoid any n+1 issues?

        1
        1. Responding to laariane-amine
          @tomgobich

          When working with many records and you can use preload, like in the example provided above, yes!

          0