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

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

问题描述

我们假设我检索一个实体 $ e 并用setter修改它的状态:

  $ E-> setFoo( 'A'); 
$ e-> setBar('b');

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



如果我的示例我想要检索 foo => a,bar => b 因此



PS:是的,我知道我可以修改所有的访问器并手动实现这个功能,但是我正在寻找一些方便的方式

解决方案

您可以使用
Doctrine\ORM\ EntityManager#getUnitOfWork 获取 Doctrine\ORM\UnitOfWork



然后仅通过 Doctrine\ORM\UnitOfWork#computeChangeSets()触发更改集计算(仅在托管实体上工作)。



您可以使用类似的方法,如 Doctrine\ORM\UnitOfWork#recomputeSingleEntityChangeSet(Doctrine\ORM\ClassMetadata $ meta,$ entity)如果您确切知道您可以在不迭代整个对象图的情况下进行检查。



之后,您可以使用 Doctrine\ORM\UnitOfWork#getEntityChangeSet($ entity )以检索对象的所有更改。



将其放在一起:

  $ entity = $ em-> find('My\Entity',1); 
$ entity-> setTitle('Changed Title!');
$ uow = $ em-> getUnitOfWork();
$ uow-> computeChangeSets(); //不要在监听器内计算更改
$ changeset = $ uow-> getEntityChangeSet($ entity);

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


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?

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

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

解决方案

You can use Doctrine\ORM\EntityManager#getUnitOfWork to get a Doctrine\ORM\UnitOfWork.

Then just trigger changeset computation (works only on managed entities) via Doctrine\ORM\UnitOfWork#computeChangeSets().

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

After that you can use Doctrine\ORM\UnitOfWork#getEntityChangeSet($entity) to retrieve all changes to your object.

Putting it together:

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

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 2实体中所有更改/更新的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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