0

I'm trying to find existence of certain Permissions on a single parent Role (many-to-many).

const roles = await Role
  .query()
  .preload('permissions')

this.role = roles.find(role => role.id === someid)

const exists = this.role.permissions.some(permission => permission.name === 'something')

This is the solution so far, which seems not optimal. Is there a way to do this without loading all the roles and permissions and looping through them in Javascript? Thank you so much

Jordan Nelson
  • 453
  • 6
  • 17

1 Answers1

1

Try using whereHas (https://docs.adonisjs.com/reference/orm/query-builder#wherehas):

await Role.query()
  .where('id', someid)
  .whereHas('permissions', q => {
    q.where('name', 'something')
  })
hlozancic
  • 1,489
  • 18
  • 31
  • Get count of found rows, or just check if it finds anything to know if permission exists on role of someid – hlozancic Mar 17 '22 at 07:52
  • The Adonis creator gave me the same solution. https://github.com/adonisjs/core/discussions/3633#discussioncomment-2377496 – Jordan Nelson May 04 '22 at 20:14