persist new entity onFlush

浪子不回头ぞ 提交于 2020-01-03 11:29:34

问题


I try to user the onFlush Event in Doctrine to persist a new entity, but it leads to an infinite loop when trying to persist. Here is what I do in the Listener:

$countusers = $em->getRepository('DankeForumBundle:NotificationUser')->countNotificationsByDeal($entity);
if ($countusers > 0) {
  $notification = new NotificationAction();
  $notification->setDeal($entity);
  $notification->setDatepost(new \DateTime());
  $notification->setNotificationtype(NotificationAction::TYPE_TOP_DEAL);
  // $em is set to EntityManager
  $em->persist($notification);
  // $uow ist set to UnitOfWork
  $uow->computeChangeSet($em->getClassmetadata('Danke\ForumBundle\Entity\NotificationAction'), $notification);
}

I know that I would get a loop, when I was flushing in the onFlush Event, but I don't do that! I only compute the new change set as it says in the documentation.

Can someone tell where the problem is?

EDIT: It maybe interesting, that I am sure it worked some days ago, but I can't remember changing anything (which I know can't be true ;) )...


回答1:


I had similar issues with onFlush Event. Please change

$em->persist($notification);

to

$uow = $em->getUnitOfWork();
$uow->persist($notification);

$metadata = $em->getClassMetadata(get_class($notification));
$uow->computeChangeSet($metadata, $notification);

$uow->persist() will make the UnitOfWork know about the new entity and will schedule it for insertion. Calling $uow->computeChangeSet() is neccessary, to collect the data that should be inserted by Doctrine's persister.



来源:https://stackoverflow.com/questions/10796496/persist-new-entity-onflush

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!