如何检查 Doctrine 2 中的实体是否更改?
我需要检查持久化实体是否已更改并需要在数据库中更新.我所做的(但没有工作)如下:
I need to check if a persisted entity has changed and needs to be updated on the database. What I made (and did not work) was the following:
$product = $entityManager->getRepository('Product')->find(3);
$product->setName('A different name');
var_export($entityManager->getUnitOfWork()->isScheduledForUpdate($product));
那个代码总是打印false
,我也试过在检查工作单元之前flush,但是没有用.
That code prints always false
, I also tried to flush before check the unit of work, but did not work.
有人有什么建议吗?
推荐答案
我首先要检查的是你的 setName 函数实际上在做什么($this-> name = $name...) 如果它已经在工作,那么您可以在 services.yml 上定义一个事件侦听器,当您调用刷新时触发.
The first thing I'd check it that your setName function is actually doing something ($this-> name = $name...) If it's already working, then you could define an event listener on your services.yml that is triggered when you call the flush.
entity.listener:
class: YourNameYourBundleEventListenerEntityListener
calls:
- [setContainer, ["@service_container"]]
tags:
- { name: doctrine.event_listener, event: onFlush }
然后你定义EntityListener
Then you define the EntityListener
namespace YourNameYourBundleEventListener;
use DoctrineORMEvent;
use SymfonyComponentDependencyInjectionContainerAware;
class EntityListener extends ContainerAware
{
/**
* Gets all the entities to flush
*
* @param EventOnFlushEventArgs $eventArgs Event args
*/
public function onFlush(EventOnFlushEventArgs $eventArgs)
{
$em = $eventArgs->getEntityManager();
$uow = $em->getUnitOfWork();
//Insertions
foreach ($uow->getScheduledEntityInsertions() as $entity) {
# your code here for the inserted entities
}
//Updates
foreach ($uow->getScheduledEntityUpdates() as $entity) {
# your code here for the updated entities
}
//Deletions
foreach ($uow->getScheduledEntityDeletions() as $entity) {
# your code here for the deleted entities
}
}
}
如果您需要知道哪些实体正在被更改,但在将它们保存到数据库之后对它们进行处理,只需将更改的实体存储在私有数组中,然后定义一个从数组中获取实体的 onFlush 事件.
If you need to know which entities are being changed, but do something with them after they've been saved to the database, just store the entities changed in a private array, an then define a onFlush event that gets the entities from the array.
顺便说一句,要触发此类事件,您需要在实体上添加 @ORMHasLifecycleCallbacks.
BTW, to trigger this kind of events you need to add the @ORMHasLifecycleCallbacks on the entity.
相关文章