6

I'm trying to detect changes in a many-to-many relation in an onFlush event.

If new entities are added to the relation or the relation is updated (always keeping an element), I can detect changes using $unitOfWork->getScheduledCollectionUpdates() and then check for getInsertDiff() or getDeleteDiff(). So far so good.

The problem comes when I take all the entities out of the relation: "There were two related entities before but there are NO related entities now."

When the relation is left empty I can access $unitOfWork->getScheduledCollectionDeletions(), but there is no way of knowing which entities were deleted:

  • getDeleteDiff() for this collections doesn't tell anything.
  • getSnapshot() doesn't tell me which entities were there before

How should I know which entities were taken out of the many-to-many relation?


I've added a Gist with the full implementation: everything works ok (it may need some optimization) except $uow->getScheduledCollectionDeletions() (line 101)

https://gist.github.com/eillarra/5127606

5
  • $uow->getScheduledCollectionUpdates() and $uow->getScheduledCollectionDeletions() both return arrays of collections. And those collections behave independently of where they are used. What exactly are you trying to accomplish? It seems like you want to "do something" with entities that are inserted or deletion into/from the db. If this is true, then you only need $uow->getScheduledEntityInsertions() (which will contain all entities that will be inserted) and $uow->getScheduledEntityDeletions() (which will contain all entities that will be deleted). Mar 12, 2013 at 19:42
  • The only other rows that are inserted/deleted are those of join-tables (many-to-many associations), but those are not entities. Mar 12, 2013 at 19:43
  • What I'm trying to do is to keep a COUNTER updated. You can see it in the code atached in Gist. Basically: I have a Post model with related Label (many-to-many) and User (many-to-one) models. The only scenario I don't control is when I delete all the Labels that a Post had before. This "deleted rows/entities" should be registered in $uow->getScheduledCollectionDeletions(), but I can't find any reference to the deleted Labels there. I'm sure the solution is pretty easy, but I can't find any documentation online...
    – eillarra
    Mar 13, 2013 at 8:14
  • When you say "delete all the Labels that a Post had", do you mean you are actually deleting the Label entities? Or are you just removing them from the association with Post (so the labels themselves remain in the db)? Mar 13, 2013 at 11:54
  • I'm removing them from the association. It's all about detecting what happens in the relations so that I can update counters in the related entities.
    – eillarra
    Mar 13, 2013 at 14:13

3 Answers 3

9
+250

The cause of this problem is twofold:

1) When the method clear() is called on a Doctrine\ORM\PersistentCollection, it will:

  1. clear its internal collection of entities.
  2. call scheduleCollectionDeletion() on the Doctrine\ORM\UnitOfWork.
  3. take a new snapshot of itself.

Number 2 is the reason your collection shows up in $uow->getScheduledCollectionDeletions() (and not in $uow->getScheduledCollectionUpdates()). Number 3 is the reason why you cannot determine what was in the collection before it was cleared.

2) When using the Symfony2 Form component, specifically the ChoiceType or CollectionType types in combination with the option multiple, that clear() method will get called when all entities should be removed from the collection.

This is due to the MergeDoctrineCollectionListener which is added here: https://github.com/symfony/symfony/blob/master/src/Symfony/Bridge/Doctrine/Form/Type/DoctrineType.php#L55

This is done as optimization: It's faster to clear a collection this way, in stead of checking which entities should be removed from it.

I can think of two possible solutions:

1) Create a fork symfony/symfony and implement an option in order to not add the MergeDoctrineCollectionListener. Maybe something like no_clear to prevent the listener from being added. This won't introduce a BC break and would solve your problem because the clear() method of a collection won't get called when all entities should be removed.

2) Redesign your counter: Maybe also listen to the OnLoad event which can count the amount of entities in the collection at the time it's fetched from the db. That way your OnFlush listener can use that number to know how many entities where removed from the collection when it was cleared.

8
  • That's what I thought too: that $uow->getScheduledCollectionUpdates() was managing everything, but is not like that. There is maybe something wrong in my code, but this is how it behaves: a) new insertions are detected by $collection->getInsertDiff(); b) removals, as long as at least one element is left in the relation, are detected by $collection->getDeleteDiff(); but c) if all elements are taken from the relation (all labels deleted for a post, for example), then $uow->getScheduledCollectionUpdates() is empty.
    – eillarra
    Mar 13, 2013 at 20:11
  • For c) $uow->getScheduledCollectionDeletions() exists, but I have no idea of where to look for the information about the removed entities. $collection->toArray() is empty in this case.
    – eillarra
    Mar 13, 2013 at 20:19
  • Could you share all code that removes the labels from the collection? Or maybe better: the complete Post entity? Mar 13, 2013 at 21:30
  • Updated the Gist with Post and Label entities: gist.github.com/eillarra/5127606
    – eillarra
    Mar 13, 2013 at 21:42
  • 1
    Can you change getLabels() (in Post) to return $this->labels->toArray();? And do the same with any other collections you have. This will make sure the collection objects never leave the entities. Mar 13, 2013 at 22:02
0

I found that if set 'by_reference' => false, option to EntityType form, then UnitOfWork detect changes of collection. See difference state in UnitOfWork at OnFlush event:

'by_reference' => false

'by_reference' => false

'by_reference' => true

'by_reference' => true

0

In case the last item gets removed (like on a form submission), the "getDeleteDiff" sometimes turns out to be empty but in reality, items were there, the solution is to fetch the original data from the database. In my example we use a clone of the collection to achieve it. So the original collection stays untouched and everything still works.

public function onFlush(OnFlushEventArgs $args)
{
    $uow = $args->getEntityManager()->getUnitOfWork();
    
    foreach ($uow->getScheduledCollectionDeletions() as $collection) {
        /**
         * "getDeleteDiff" is not reliable, collection->clear on PersistentCollection also clears the original snapshot
         * A reliable way to get removed items is: clone collection, fetch original data
         */
        $removedData = $collection->getDeleteDiff();
        if (!$removedData) {
            $clone = clone $collection;
            $clone->setOwner($collection->getOwner(), $collection->getMapping());
            // This gets the real data from the database into the clone
            $uow->loadCollection($clone);

            // The actual removed items!
            $removedData = $clone->toArray();
        }
    }
}

The reason the ->getDeleteDiff() is sometimes empty is because the "onSubmit" function of a form calls the ->clear() function on a PersistentCollection. And by clearing it, the original "snapshot" gets cleared too (for performance reasons I guess). And the "getDeleteDiff" function actually relies on that snapshot, but now it's empty.

There are multiple issues on Github about this problem:

https://github.com/doctrine/orm/issues/2272

https://github.com/doctrine/orm/issues/4173

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.