我有两个控制器,一个记录修改过的实体并将它们放在一个会话中:
public function update_accountAction(Request $request)
{
Try
{
$code = $request->request->get('code');
$name = $request->request->get('name');
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('NRtworksChartOfAccountsBundle:Accounttree');
$to_change = new Accounttree();
$to_change = $repo->findOneByCode($code);
$to_change->setName($name);
$to_change->setCode($code);
$session = $this->getRequest()->getSession();
$entity_to_update = $session->get('entity_to_update');
$counter = $session->get('number_of_changes');
$entity_to_update[] = $to_change;
$counter = $counter +1;
$session->set('number_of_changes',$counter);
$session->set('entity_to_update',serialize($entity_to_update));
$response = array("code" => 100, "success" => true, "modified" => $entity_to_update);
return new Response(json_encode($response));
}
Catch(Exception $e)
{
$response = array("code" => 100, "success" => false, "error" => $e);
return new Response($response);
}
}
另一个循环结果,如果它实际上是一个期望的对象持续它。最后我冲了过来。
public function save_changesAction()
{
Try
{
$em = $this->getDoctrine()->getManager();
$session = $this->getRequest()->getSession();
$entity_to_update = unserialize($session->get('entity_to_update'));
foreach($entity_to_update as $account)
{
if($account->getId())
{
$em->persist($account);
echo $account->getId();
}
else
{
echo "error";
}
}
$em->flush();
$response = array("code" => 100, "success" => true, "modified" => $account->getId());
return new Response(json_encode($response));
}
Catch(Exception $e)
{
$response = array("code" => 100, "success" => false, "error" => $e);
return new Response($response);
}
}
所以结果是: ContextErrorException:注意:/home/eagle1/www/Symfony24/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php第2852行中未定义的索引:000000007a60b041000000007ae6afd8
我不明白为什么,因为我似乎回到了一个功能齐全的对象(我可以执行它的功能,访问它的属性,而且似乎还有持久性工作......
有人知道答案吗?
答案 0 :(得分:2)
当您从会话中提取对象时,它不受学说管理。您必须将其合并回来通知实体经理。
if($account->getId())
{
$account = $em->merge($account);
$em->persist($account);
echo $account->getId();
}
Doctrine有Entities in the Session
的手册部分