Query inside a Model


#1

Hi,

I have the following Model:

'use strict'

const Model = use('Model')

class User extends Model {
  static get hidden () {
    return ['password', 'email']
  }

  static boot () {
    super.boot()
    this.addHook('beforeCreate', 'UserHook.hashPassword')
  }

  group () {
    return this.belongsTo('App/Models/Group')
  }

  tokens () {
    return this.hasMany('App/Models/Token')
  }
}

module.exports = User

How can I create a method that can execute a query?

For example:

// ...

class User extends Model {
  // ...

  getPermissions () {
    this.query()
       .with('group.permissions')
      // ...
  }
}

How can I do somethins like that?

Thanks a lot. :slight_smile:


#2

You can try to use a query scope

https://adonisjs.com/docs/4.1/lucid#_query_scopes

don’t know exactly what is your use case and what do you try to achieve


#3

I’ve discovered how to do that with traits.

https://adonisjs.com/docs/4.1/traits