Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 3 / Doctrine - Get changes to associations in entity change set

So I already know that I can get changes to a specific entity in the preUpdate lifecycle event:

/**
 * Captures pre-update events.
 * @param PreUpdateEventArgs $args
 */
 public function preUpdate(PreUpdateEventArgs $args)
 {
     $entity = $args->getEntity();


     if ($entity instanceof ParentEntity) {
            $changes = $args->getEntityChangeSet();
     }
 }

However, is there a way to also get changes for any associated Entities? For example, say ParentEntity has a relationship setup like so:

/**
 * @ORM\OneToMany(targetEntity="ChildEntity", mappedBy="parentEntity", cascade={"persist", "remove"})
 */
 private $childEntities;

And ChildEntity also has:

/**
 * @ORM\OneToMany(targetEntity="GrandChildEntity", mappedBy="childEntity", cascade={"persist", "remove"})
 */
 private $grandChildEntities;

Is there a way to get all relevant changes during the preUpdate of ParentEntity?

like image 841
Darkstarone Avatar asked Jul 16 '17 06:07

Darkstarone


1 Answers

All of the associated entities from a OneToMany or ManyToMany relationships appear as a Doctrine\ORM\PersistentCollection.

Take a look at the PersistentCollection's API, it have some interesting public methods even if they are marked as INTERNAL: https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/PersistentCollection.php#L308

For example you can check if your collection is dirty which means that its state needs to be synchronized with the database. Then you can retrieve the entities that have been removed from the collection or inserted into it.

if ($entity->getChildEntities()->isDirty()) {
    $removed = $entity->getChildEntities()->getDeleteDiff();
    $inserted = $entity->getChildEntities()->getInsertDiff();
}

Also you can get a snapshot of the collection at the moment it was fetched from the database: $entity->getChildEntities()->getSnapshot();, this is used to create the diffs above.

like image 135
rpg600 Avatar answered Oct 23 '22 18:10

rpg600