Is there a built-in way to get all of the changed/updated fields in a Doctrine 2 entity(是否有内置方法来获取 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()
.
如果您确切地知道要检查的内容而无需遍历整个对象图.
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 实体中所有更改/更新的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否有内置方法来获取 Doctrine 2 实体中所有更改/更新的字段
基础教程推荐
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01