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
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.