我做了一个监听器,以便在每次INSERT和UPDATE时更新一些字段:
public function onFlush(OnFlushEventArgs $eventArgs)
{
$token = $this->container->get('security.context')->getToken();
$em = $eventArgs->getEntityManager();
$uow = $em->getUnitOfWork();
// Inserts
foreach ($uow->getScheduledEntityInsertions() as $entity) {
if (is_subclass_of($entity, 'Kiwi\Bundle\TrainingBundle\Entity\EntityDated')) {
$entity->setCreated(new \Datetime());
$entity->setCreatedBy($token->getUser()->getUsername());
$entity->setUpdated(new \Datetime());
$entity->setUpdatedBy($token->getUser()->getUsername());
$meta = $em->getClassMetadata(get_class($entity));
$uow->recomputeSingleEntityChangeSet($meta, $entity);
}
}
// Updates
foreach ($uow->getScheduledEntityUpdates() as $entity) {
if (is_subclass_of($entity, 'Kiwi\Bundle\TrainingBundle\Entity\EntityDated')) {
$entity->setUpdated(new \Datetime());
$entity->setUpdatedBy($token->getUser()->getUsername());
$meta = $em->getClassMetadata(get_class($entity));
$uow->recomputeSingleEntityChangeSet($meta, $entity);
}
}
}
我将以OneToMany Response为例介绍一个实体问题。
在这种情况下,这非常有效:
唯一不起作用的案例是:
当我做最后一个案例时,我的链接实体被删除(响应)但我的主要实体(问题)没有更新。
这是我的控制器,也许问题出在这里:
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
foreach ($originalResponses as $response) {
if ($qc->getQuestionClosedResponses()->contains($response) == false) {
$em->remove($response);
}
}
foreach ($qc->getQuestionClosedResponses() as $response) {
$response->setQuestionClosed($qc);
$em->persist($response);
}
$em->persist($qc);
$em->flush();
return $this->redirect($this->generateUrl('kiwi_training_questionclosed'));
}
答案 0 :(得分:0)
问题不是来自听众而是来自控制器。 这是新的控制器工作:
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
foreach ($qc->getQuestionClosedResponses() as $response) {
$response->setQuestionClosed($qc);
$em->persist($response);
}
$em->persist($qc);
$em->flush();
foreach ($originalResponses as $response) {
if ($qc->getQuestionClosedResponses()->contains($response) == false) {
$em->remove($response);
}
}
$em->persist($qc);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'Votre question fermée a bien été modifiée');
return $this->redirect($this->generateUrl('kiwi_training_questionclosed'));
}
我必须在删除和编辑之间进行新的持久/刷新。