Open achterberatung opened 4 years ago
The problem is that you're overriding the persistent collection, which is not the intended usage for that. Have you tried this (on the second run):
$main = $mainRepo->find(1);
$main->setText("test");
$em->flush();
$s1 = $secondRepo->find(1);
$main->getSecond()->clear();
$main->getSecond()->add($s1);
$em->flush();
@achterberatung Did the answer help with your problem? If you consider this done, we could close this issue.
@lcobucci Unfortunately our real code of course is a little bit more complicated. We have a separation of the doctrine entity and our data-framework. So since we are using doctrine, we had the collections in ManyToX-Associations generated new without knowledge of the original collection. And this never was a problem, until we needed to do a double flush because of including some legacy business functions, which are directly interacting with the database. Refactor that would be much more effort and a break of our separation concept, so patching doctrine the way i showed is much more suitable for us.
@SenseException Maybe we are misusing doctrine to reproduce it, but my bug ticket shall show, that after a flush the originalEntityData is by definition in a faulty state, because elements are missing. When first loading the PersistentCollection, it is written to originalEntityData, but by doing a flush, they are just sortet out, because they already know their parent entity. Any other data is still written to originalEntityData. And everything works well, if I put these ignored collections in an array and appending them to the new originalEntityData.
If you do not consider as a bug, maybe we can convert it to a feature request?
I'm not sure if I understand it right. Can you please provide us a PR with a failing test closer to your use case so we can evaluate if this is an edge case or a possible feature request? It looks like the first example doesn't really cover the problem you have for a suitable fix.
Bug Report
Summary
When flushing an Entity with ManyToMany-association, originalEntityData is written new (of course). But the (old) PersistentCollection is not added to the new originalEntityData. Changing the collection inside the entity let doctrine think, the collection is all new, resulting in duplicate key errors from database.
Current behavior
After a flush, doctrine tries to insert elements of a ManyToMany-association even if they are already in the database.
How to reproduce
Given two Entities:
and corresponding repositories you can reproduce the Bug.
First initialize some Data with given $em, $mainRepo and $secondRepo:
Now (i've done it in a second request) reproduce the bug:
Results in:
Expected behavior
also ignored collection have to get into originalEntityData.
My Quickfix in UnitOfWork: