objection.js icon indicating copy to clipboard operation
objection.js copied to clipboard

Relations to the same model dissapear when unlinking

Open prk3 opened this issue 7 years ago • 7 comments

When model A has two or more relations (let's call them x and y) to class B, then unlinking A.B though relation x affects existing links though y (these get unlinked too).

Here is the repo with code reproducing this bug (you can check out the only PR to see what has changed in relation to reproduction-template). https://github.com/prk3/objection-bug-disappearing-relations

prk3 avatar Jul 08 '19 14:07 prk3

If the two relations are linked through the same join table or the same foreign key, then yes, that's expected.

koskimas avatar Jul 08 '19 14:07 koskimas

And please, avoid upsertGraph like the plague! I will be heavily discouraging its usage in 2.0.

koskimas avatar Jul 08 '19 14:07 koskimas

If the two relations are linked through the same join table or the same foreign key, then yes, that's expected.

Even when there is an "extra" and "modify" for distinguishing links? It's pretty obvious that there is a problem with representing relations like this. Take a look at this issue: https://github.com/Vincit/objection.js/issues/1268

And it's not only a problem with upsertGraph. I've refactored the code so that it doesn't use upserts and the problem persists (it actually got worse, as relating appears to be broken too). You can see the code in reproduction repo.

prk3 avatar Jul 08 '19 16:07 prk3

This issue will actually be resolved by #1356

koskimas avatar Jul 08 '19 20:07 koskimas

So the issue is that the modify and beforeInsert are for the related table, not for the pivot table. #1356 will make it possible to add modify and beforeInsert for the pivot table.

By the way, this does nothing:

 modify: qb => qb.relation === 'pet'

We cannot run javascript in the database. You need to use

 modify: qb => qb.where('relation', 'pet')

koskimas avatar Jul 08 '19 20:07 koskimas

I need to set a value on the pivot table row when it's inserted (M:N relation). Will that be possible too? (not just querying)

contextlimit avatar Jul 16 '19 07:07 contextlimit

@ericmuyser That's already possible. https://vincit.github.io/objection.js/recipes/extra-properties.html#join-table-extra-properties

koskimas avatar Jul 18 '19 19:07 koskimas