我需要检查持久化实体是否已更改并需要在数据库中更新。 我所做的(但没有工作)如下:
$product = $entityManager->getRepository('Product')->find(3);
$product->setName('A different name');
var_export($entityManager->getUnitOfWork()->isScheduledForUpdate($product));
那个代码总是打印false
,我也试过在检查工作单元之前flush,但是没有用。
有人有什么建议吗?
最佳答案
我首先会检查你的 setName 函数是否确实在做某事($this-> name = $name...)如果它已经在工作,那么你可以定义一个事件调用刷新时触发的 services.yml 上的监听器。
entity.listener:
class: YourName\YourBundle\EventListener\EntityListener
calls:
- [setContainer, ["@service_container"]]
tags:
- { name: doctrine.event_listener, event: onFlush }
然后定义EntityListener
namespace YourName\YourBundle\EventListener;
use Doctrine\ORM\Event;
use Symfony\Component\DependencyInjection\ContainerAware;
class EntityListener extends ContainerAware
{
/**
* Gets all the entities to flush
*
* @param Event\OnFlushEventArgs $eventArgs Event args
*/
public function onFlush(Event\OnFlushEventArgs $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
}
}
}
如果您需要知道哪些实体正在被更改,但在它们被保存到数据库后对它们做一些事情,只需将更改的实体存储在一个私有(private)数组中,然后定义一个从数组中获取实体的 onFlush 事件。
顺便说一句,要触发此类事件,您需要在实体上添加 @ORM\HasLifecycleCallbacks。
关于php - 如何检查 Doctrine 2 中的实体是否更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10800178/