我有自我引用的一对多关系(我是根据文档做的:http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-many-self-referencing)
现在我想要将新元素刷新到Entity,但是如何使用新的flush元素的ID将它放在引用位置?
我尝试:
$newProject->setSubprojectId($newProject);
和:
$newProject->setSubprojectId($newProject->getId());
但我认为在刷新之前无法获取对象的ID。我没错?
我的代码如下:
/**
* @Route("/project/manage", name="project_edit");
*/
public function registerAction(Request $request)
{
$user = $this->get('security.token_storage')->getToken()->getUser();
$newProject = new Project();
$newProject->setIsActive(1);
$newProject->setOwner($user);
$newProject->setCreateDate( new \DateTime() );
$newProject->setSubprojectId($newProject);
$formProject = $this->createForm(AddProject::class, $newProject);
$formProject->handleRequest($request);
if($formProject->isSubmitted() && $formProject->isValid()){
$em = $this->getDoctrine()->getManager();
$em->persist($newProject);
$em->flush();
return $this->render('xxx/projectEdit.html.twig', array(
'form' => $formProject->createView(),
));
}
return $this->render('xxx/projectEdit.html.twig', array(
'form' => $formProject->createView(),
));
}
修改
我找到了不同的解决方案,但问题仍然有效 - 可以在刷新之前获取此ID或同时刷新两列的ID吗?
答案 0 :(得分:0)
您可以尝试设置级联持久性,但为什么不这样做:
$em = $this->getDoctrine()->getManager();
$em->persist($newProject);
$em->flush();
$newProject->setSubProject($newProject); // *why* do you want to do this?
$em->persist($newProject);
$em->flush();
您不应该直接设置ID。您应该能够通过在对象上使用setter来完成此操作,并且doctrine应该为您处理id。