问题描述
假设我检索一个实体 $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 useDoctrineORMEntityManager#getUnitOfWork
to get a DoctrineORMUnitOfWork
.
然后只需通过 DoctrineORMUnitOfWork#computeChangeSets()
触发变更集计算(仅适用于托管实体).
Then just trigger changeset computation (works only on managed entities) via DoctrineORMUnitOfWork#computeChangeSets()
.
如果您确切地知道要检查的内容而无需遍历整个对象图.
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 实体中所有更改/更新的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!