Creating own scope for fetch

My User model has relationship with Role, Profile, Type and some others

 const Model = use('Model')

class User extends Model {
    profile() {
        return this.hasOne('App/Models/Profile')

    role() {
        return this.belongsTo('App/Models/Role')

    type() {
        return this.belongsTo('App/Models/Type')

    addresses() {
        return this.hasMany('App/Models/Address')

I am able to fetch data by calling with as

Is their a way I created my own fetch like function in which these relations are already defined I just need to call like this


I did not tried this

something like this ?

class User extends Model {
    fetchAll() {
        return this.query().with('role').with('addresses').with('type').fetch()
1 Like

Exactly like this :slight_smile:

You might be able to make it more manageable with something like this:

 * Array of all relations in separate getter / function
 * so you can use Model.relations in some other place too to get
 * array of all relations
get relations () {
  return  [

// Fetch all relations
  let query = this.query()
  this.relations.ForEach(relation => {
    query = query.with(relation)
  return query.fetch()

It won’t be much cleaner if you only want to fetch all, but if sometimes you want to get list of all relations and sometimes fetch them all, then it’s good way to do it :slight_smile: