B
B
bears2018-09-27 17:14:52
symfony
bears, 2018-09-27 17:14:52

How to get Doctrine entities removed from collection?

Friends, it became necessary to keep track of which entities were removed from the associated many-to-many collection, but then I came across a strange bug (maybe a feature?).
Given: there are 2 entities - User and Car. There is a common many-to-many relationship between them. If you do this:

// echo $user->getCars()->count(); = 1

$car = $user->getCars()->get(0);

$user->removeCar($car);

var_dump($user->getCars()->getDeleteDiff()); // тут есть удаленный элемент

then everything works great. But if you do it like this:
// echo $user->getCars()->count(); = 1

$car = $user->getCars()->get(0);

$user->getCars()->clear();
$user->addCar($car);
$user->removeCar($car);

var_dump($user->getCars()->getDeleteDiff()); // пустой массив

then no. Empirically revealed that after the call, the $user->getCars()->clear();
doctrine can no longer understand which entities are removed from the collection. Just as shown in the code above, after ->clear(), you can add other entities to the collection and remove them, but still the result is the same - an empty array. If someone came across, please direct in which direction to dig.
The problem is aggravated by the fact that the project is working, and these entities are edited through standard symfony forms. Now, if you remove all related entities, then apparently symfony calls the same clear ().
PS Surprisingly, getInsertDiff always works as it should, but getDeleteDiff does not.
$car = $user->getCars()->get(0);
$user->getCars()->clear();
$user->addCar($car);
var_dump($user->getCars()->getInsertDiff()); // тут есть добавленный элемент

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Flying, 2018-09-27
@bears

The answers to your questions, obviously, lie in the Doctrine sources:
It can be seen that the behavior of the method clear()depends on which side of the association you clear. You can also see that if you work with the owner side of the association, then Doctrine creates a new snapshot.
From the code of the getInsertDiff and getDeleteDiff methods, it can be seen that the difference is calculated by comparing the snapshot with the current contents of the collection, so it is obvious that if a new snapshot is created, the difference will be an empty array.
The easiest way to check if Symfony itself is calling a method clear()is to set a breakpoint there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question