javascriptnode.jsactiverecordadonis.jslucid

How does one find existence of (Adonis Lucid Many-to-Many) children records on one parent that meet a criteria?


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


Solution

  • 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')
      })