User Model Subquery

Hi.

I have a lot of models related to my User model with a ‘user’ relationship.

So when I want to get the models with the user data I repeat over and over the same queries. Example:

let mydata= xxxModel.query()
.where('slug',slug)
.with('user',builder=>{
  builder.with('profile',profile=>{
     profile.where('status','active')
  } 
  .with('media',media=>{
    media.where('role','profile')
  }
})
.with(....)

Is it possible to create a function in my User model to insert all this code:

builder=>{
  builder.with('profile',profile=>{
     profile.where('status','active')
  } 
  .with('media',media=>{
    media.where('role','profile')
  }
}

to the queries?

my best.

You can try

// Inside xxxModel
user () {
  return this.hasMany('App/Models/User')
    .with('profile', (builder) => {
     builder.where('status', 'active')
   })
}

Can’t test it myself currently, can’t guarantee it works, but you can edit relations however you like. Or create multiple relations like user, userWithProfile, userWithAllStuff etc

1 Like

hi @McSneaky.

Thanks for your answer, interesting approach. I’ll try it.

BR