问题
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