Reusable Query Statements with Model Query Scopes

In this lesson, we'll learn about Model Query Scopes and how we can use them to create easily reusable query statements that we can apply using the Model Query Builder.

Published
Mar 11
Duration
8m 11s

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 6 months ago

    My assumption to this lesson is that the models.movies.query() is injecting SELECT * FROM movies… by default and the scope is injecting the rest you created in the model? No where in the model or its seen that SELECT * FROM movies… its written anywhere.

    1

    Please sign in or sign up for free to reply

    1. Commented 6 months ago

      Yes, the model query builder will always provide a query scoped specifically to the model's table. If you don't specify a select within the query you're building, it will default to selecting all columns, which can be denoted by *. So, some examples:

      await Movie.query()
      // Result: SELECT * FROM movies
      
      await Cineast.query().select('id')
      // Result: SELECT id FROM cineasts
      
      await Movie.query().select('slug').where('title', 'Interstellar')
      // Result: SELECT slug FROM movies WHERE title = 'Interstellar'
      Copied!
      1

      Please sign in or sign up for free to reply

      1. Commented 6 months ago

        Interesting….
        I'm coming from writing APIs with NestJS and this framework indeed is taking a different but interesting approach.

        1

        Please sign in or sign up for free to reply

        1. Commented 6 months ago

          I'm not very familiar with NestJS so I, unfortunately, can't provide any direct comparisons, but under the hood, AdonisJS' query builder, for both the models and the database module, is a wrapping of the KnexJS query builder.

          So, you do have access to an unrestricted query builder as well via the database query builder should you need it:

          import db from '@adonisjs/lucid/services/db'
          
          await db.from('movies').select('slug', 'title').whereNotNull('released_at')
          Copied!

          Just note that, unlike the model query builder, since the database query builder isn't going through models, naming strategies won't go into effect so you'll need to use the column names as they're defined inside the database.

          Then, you also have the static model query methods as well for more straightforward queries.

          1

          Please sign in or sign up for free to reply