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).

Published
Mar 18
Duration
5m 17s

Developer, dog lover, and burrito eater. Currently teaching AdonisJS, a fully featured NodeJS framework, and running Adocasts where I post new lessons weekly. Professionally, I work with JavaScript, .Net C#, and SQL Server.

Adocasts

Burlington, KY

Join The Discussion! (4 Comments)

Please sign in or sign up for free to join in on the dicussion.

  1. Commented 4 months ago

    is there a risk of an n+1 issue when using lazy loading? ( first comment btw :) )

    1

    Please sign in or sign up for free to reply

    1. Commented 4 months ago

      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

      Please sign in or sign up for free to reply

      1. Commented 4 months ago

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

        1

        Please sign in or sign up for free to reply

        1. Commented 4 months ago

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

          0

          Please sign in or sign up for free to reply