I am learning Objection JS and love it so far. I have a manyToMany relationship on an accounts and roles table that are related through an accounts_roles table. I was wondering if there was a way to update account roles on the account model by doing something like:
AccountOne.addRoles([roleId])
AccountOne.removeRoles([roleId])
AccountOne.updateRoles([roleId])
AccountOne.deleteRoles([roleId])
I searched online and went through the official objection documentation. So far I can do a GraphInsert, on my account model with a role object "x", and that creates a new role "x" with a relationship correctly defined in accounts_roles. But that always creates a new role. I would like to add and remove relationships between existing accounts and roles. Any help would be much appreciated.
Thanks koskimas, just what I needed. Your responses to other inquiries here have also helped me a lot. Thanks for being so active in this community. I tried out the relate and unrelate method, and they work great. I noticed that the relate method can create duplicate associations, is there a way to prevent that?
So far I thought of (A) either removing the existing associations from the to be associated array or (B) delete all associations before updating similar to Laravel's Eloquent sync(). Would you recommend A / B or Is there a better way of achieving this?
Happy to help :beers:
All options where you first remove rows and then add rows, or check existence and then add rows, will be open to concurrency related bugs if locks and transactions are not used correctly. I'd suggest adding an unique constraint for the foreign key pair in the pivot table. That way you get an error if the row already exists, which you can then ignore. You can use the objection-db-errors plugin and do some thing like this
try {
await something.$relatedQuery('someRelation').relate(someId)
} catch (err) {
// Ignore unique violation.
if (!(err instanceof UniqueViolationError)) {
throw err
}
}
Most helpful comment
Happy to help :beers:
All options where you first remove rows and then add rows, or check existence and then add rows, will be open to concurrency related bugs if locks and transactions are not used correctly. I'd suggest adding an unique constraint for the foreign key pair in the pivot table. That way you get an error if the row already exists, which you can then ignore. You can use the
objection-db-errorsplugin and do some thing like this