我正在尝试在preFlush事件上向实体添加用户实体。基本上每个实体都有一个createdBy,它是一个User实体。
每当我尝试这个时,我都会收到以下错误。
Notice: Undefined index: 0000000055f036b6000000009c9cc58f in /dir/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 870
这是我的preFlush功能。
public function preFlush(PreFlushEventArgs $args)
{
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();
$securityContext = $this->container->get('security.context');
if($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')
|| $securityContext->isGranted('IS_AUTHENTICATED_FULLY'))
{
$user = $securityContext->getToken()->getUser();
}
if(!$user)
{
$user = $em->getRepository('NAB\EnterpriseBundle\Entity\User')->findOneByUsername($this->username);
}
foreach ($uow->getScheduledEntityInsertions() as $entity)
{
$entity->setCreatedBy($user);
$em->persist($user);
}
$meta = $em->getClassMetadata(get_class($entity));
$uow->recomputeSingleEntityChangeSet($meta, $entity);
$uow->computeChangeSets($meta, $entity);
}
我做错了什么?
答案 0 :(得分:3)
您正在错误地计算更改集。以下位:
$meta = $em->getClassMetadata(get_class($entity));
$uow->recomputeSingleEntityChangeSet($meta, $entity);
$uow->computeChangeSets($meta, $entity);
仅在已检查上下文中的最后一个实体上执行。
你应该把它移到你的foreach:
foreach ($uow->getScheduledEntityInsertions() as $entity) {
$entity->setCreatedBy($user);
$em->persist($user);
$meta = $em->getClassMetadata(get_class($entity));
$uow->recomputeSingleEntityChangeSet($meta, $entity);
}
更好(因为您不熟悉UnitOfWork
API),您可以在最后重新计算所有变更集一次:
foreach ($uow->getScheduledEntityInsertions() as $entity) {
$entity->setCreatedBy($user);
$em->persist($user);
}
$uow->computeChangeSets();
您还应该将此侦听器从preFlush
移至onFlush
,以处理其他侦听器应用的任何更改。