Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

many-to-any relation delete #129

Closed
olaulau opened this issue Mar 20, 2024 · 1 comment
Closed

many-to-any relation delete #129

olaulau opened this issue Mar 20, 2024 · 1 comment

Comments

@olaulau
Copy link

olaulau commented Mar 20, 2024

Hi ;

Let's say we have modelA <-> modelB linked by a many-any relation (and a pivot table).
I can use $modelA->Bs to get every modelB linked to my modelA.

Now if I try to set this relation, I can write : $modelA->Bs = [1, 2, 3], 1, 2, 3 being IDs of my modelB I want to link.
This works.

Viewing the DB logs, it seems that cortex deletes all before inserting them again (one by one).
Although it's useless (if I only remove one of the IDs), if we have other data linked, it can be problematic (and fail due to FK constraint).

Using only collections (no array of IDs), we can add with this syntax : $modelA->Bs [] = $b.
How about to remove one ?
I tried this :

foreach($modelA->Bs as $i => $bs) {
    unset($modelA->Bs [$i]);
}
$modelA->save();

but it didn't work.

Any idea ?
I think I will fallback querying directly the pivot table, but it sucks.

@ikkez
Copy link
Owner

ikkez commented Jan 19, 2025

Viewing the DB logs, it seems that cortex deletes all before inserting them again (one by one).

fixed this issue in the latest commit. Hope this helps.

Regarding unset($modelA->Bs [$i]); ... this is problematic, because PHP uses a reference to update the underlaying array. The way it is implemented currently only pushes updates to the field when changing the value via set, so meaning using $modelA->Bs = $foo, because in this case it's not modified indirectly.. blame PHP for such weirdness behaviour :D

I'll certainly need to check all loaded relations and see if they have changed on saving the model to improve the usage at this point.. that's a task for another day ;)

@ikkez ikkez closed this as completed Jan 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants