in Loopback how can we find related data in the before save hook of the model?

73 Views Asked by At

I have a table user and userGroups and there is a hasAndBelongsToMany relation between userGroups and user. If I update the userGroup by adding one more user to it then I want to compare and figure out the new user added in the before save

module.exports = function (UserGroup, Model) {
  UserGroup.observe('before save', async function (ctx, next) {
    const userData = await UserGroup.find({
      filter: {
        where: {
          id: ctx.currentInstance.id
        }
      },
      include: {
        relation: 'users',
        scope: {
          include: ['userGroups']
        }
      },
      limit: 1
    })

    console.log(userData)
    return next()
  })
}

The userData includes the newly patched user whereas it should just display the users that were in the group before

1

There are 1 best solutions below

0
Apoorva Saxena On

This can be fixed by using hasManyThrough relationship (https://loopback.io/doc/en/lb3/HasManyThrough-relations.html)

Create a new table Membership and add hooks that catch whenever a new user is added to userGroup.

New membership will get created when a user is added to userGroup.