php - Symfony 3/Doctrine - 获取实体更改集中关联的更改

标签 php symfony doctrine-orm associations

所以我已经知道我可以在 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;

有没有办法在 ParentEntitypreUpdate 期间获取所有相关更改?

最佳答案

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/

相关文章:

symfony - Doctrine 查询生成器结果错误

php - 如何在 Symfony2 功能测试中使用经过身份验证的用户?

php - Zend Framework 2 - 注释表单和 Doctrine2 - 可捕获的 fatal error - ObjectManager

php - mssql和左连接重复记录

php - 警告 : mysql_select_db(): supplied argument is not a valid MySQL-Link resource

Symfony2 如何加载validation.yml

symfony - Gedmo\Translatable 忽略配置中设置的默认语言环境

php - ldap_mod_replace() [function.ldap-mod-replace] : Modify: Server is unwilling to perform

Java:同步套接字输入

symfony - 无效的PathExpression。预期的StateFieldPathExpression或SingleValuedAssociationField