Playing Next Lesson In
seconds

Let's Learn AdonisJS 6 #4.14

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.

Created by
@tomgobich
Published

Join the Discussion 4 comments

Create a free account to join in on the discussion
  1. @redeemefy

    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
    1. Responding to redeemefy
      @tomgobich

      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
      1. Responding to tomgobich
        @redeemefy

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

        1
        1. Responding to redeemefy
          @tomgobich

          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