所以我已经知道我可以在 preUpdate
生命周期事件中获取对特定实体的更改:
/**
* Captures pre-update events.
* @param PreUpdateEventArgs $args
*/
public function preUpdate(PreUpdateEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof ParentEntity) {
$changes = $args->getEntityChangeSet();
}
}
但是,有没有办法同时获取任何关联实体的更改?例如,假设 ParentEntity
具有如下关系设置:
/**
* @ORM\OneToMany(targetEntity="ChildEntity", mappedBy="parentEntity", cascade={"persist", "remove"})
*/
private $childEntities;
并且ChildEntity
还有:
/**
* @ORM\OneToMany(targetEntity="GrandChildEntity", mappedBy="childEntity", cascade={"persist", "remove"})
*/
private $grandChildEntities;
有没有办法在 ParentEntity
的 preUpdate
期间获取所有相关更改?
最佳答案
OneToMany 或 ManyToMany 关系中的所有关联实体都显示为 Doctrine\ORM\PersistentCollection。
看看 PersistentCollection 的 API,它有一些有趣的公共(public)方法,即使它们被标记为 INTERNAL:https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/PersistentCollection.php#L308
例如,您可以检查您的集合是否脏,这意味着它的状态需要与数据库同步。然后您可以检索已从集合中删除或插入其中的实体。
if ($entity->getChildEntities()->isDirty()) {
$removed = $entity->getChildEntities()->getDeleteDiff();
$inserted = $entity->getChildEntities()->getInsertDiff();
}
您还可以获得集合从数据库中获取时的快照:$entity->getChildEntities()->getSnapshot();
,这用于创建差异以上。
关于php - Symfony 3/Doctrine - 获取实体更改集中关联的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45125857/