Symfony 3/主义-在实体变更集中获取对关联的变更 [英] Symfony 3 / Doctrine - Get changes to associations in entity change set

查看:72
本文介绍了Symfony 3/主义-在实体变更集中获取对关联的变更的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我已经知道我可以在preUpdate生命周期事件中对特定实体进行更改:

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();
     }
 }

但是,是否有一种方法也可以获取任何关联实体的更改?例如,说ParentEntity具有如下关系设置:

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;

ChildEntity还有:

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

ParentEntitypreUpdate期间是否有办法获取所有相关更改?

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

推荐答案

来自OneToMany或ManyToMany关系的所有关联实体都显示为 Doctrine \ ORM \ PersistentCollection .

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

看看PersistentCollection的API,即使它们被标记为INTERNAL,它也有一些有趣的公共方法:

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();
}

从数据库中获取集合的快照时,您还可以获得快照:$entity->getChildEntities()->getSnapshot();,用于创建上面的差异.

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.

这篇关于Symfony 3/主义-在实体变更集中获取对关联的变更的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆