是否有一种内置方法可以获取 Doctrine 2 实体中所有更改/更新的字段 [英] Is there a built-in way to get all of the changed/updated fields in a Doctrine 2 entity

查看:22
本文介绍了是否有一种内置方法可以获取 Doctrine 2 实体中所有更改/更新的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我检索实体 $e 并使用 setter 修改其状态:

Let's suppose I retrieve an entity $e and modify its state with setters:

$e->setFoo('a');
$e->setBar('b');

是否有可能检索已更改的字段数组?

Is there any possibility to retrieve an array of fields that have been changed?

在我的例子中,我想检索 foo =>a, 条 =>b 结果

In case of my example I'd like to retrieve foo => a, bar => b as a result

PS:是的,我知道我可以修改所有访问器并手动实现此功能,但我正在寻找一些方便的方法来执行此操作

PS: yes, I know I can modify all the accessors and implement this feature manually, but I'm looking for some handy way of doing this

推荐答案

您可以使用DoctrineORMEntityManager#getUnitOfWork 得到一个 DoctrineORMUnitOfWork.

You can use DoctrineORMEntityManager#getUnitOfWork to get a DoctrineORMUnitOfWork.

然后通过 DoctrineORMUnitOfWork#computeChangeSets() 触发变更集计算(仅适用于托管实体).

Then just trigger changeset computation (works only on managed entities) via DoctrineORMUnitOfWork#computeChangeSets().

你也可以使用类似的方法,比如 DoctrineORMUnitOfWork#recomputeSingleEntityChangeSet(DoctrineORMClassMetadata $meta, $entity) 如果你确切地知道你想检查什么而不用遍历整个对象图.

You can use also similar methods like DoctrineORMUnitOfWork#recomputeSingleEntityChangeSet(DoctrineORMClassMetadata $meta, $entity) if you know exactly what you want to check without iterating over the entire object graph.

之后,您可以使用 DoctrineORMUnitOfWork#getEntityChangeSet($entity) 来检索对象的所有更改.

After that you can use DoctrineORMUnitOfWork#getEntityChangeSet($entity) to retrieve all changes to your object.

组合起来:

$entity = $em->find('MyEntity', 1);
$entity->setTitle('Changed Title!');
$uow = $em->getUnitOfWork();
$uow->computeChangeSets(); // do not compute changes if inside a listener
$changeset = $uow->getEntityChangeSet($entity);

注意.如果尝试在preUpdate 侦听器中获取更新的字段,不要重新计算更改集,因为它已经完成了.只需调用 getEntityChangeSet 即可获取对实体所做的所有更改.

Note. If trying to get the updated fields inside a preUpdate listener, don't recompute change set, as it has already been done. Simply call the getEntityChangeSet to get all of the changes made to the entity.

警告:如评论中所述,不应在 Doctrine 事件侦听器之外使用此解决方案.这将破坏 Doctrine 的行为.

Warning: As explained in the comments, this solution should not be used outside of Doctrine event listeners. This will break Doctrine's behavior.

这篇关于是否有一种内置方法可以获取 Doctrine 2 实体中所有更改/更新的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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