持久化自引用实体不起作用
Persisting self referencing entity not works
我创建了一个带有自引用的实体。我的实体看起来像这样:
class Question
{
/**
* @ORM\OneToMany(targetEntity="Question", mappedBy="parent")
**/
private $children;
/**
* @ORM\ManyToOne(targetEntity="Question", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
**/
private $parent;
}
然后我创建了一个表单来编辑问题。使用此表格,我可以将许多孩子添加到一个问题中。在我 post 这张表格之后,我将把孩子们留到 parent Object。但是 parent 的孩子的持久化失败了,数据库中没有任何反应。
public function manageDependencyAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$question = $em->getRepository('AppMyBundle:Question')->find($id);
if (!$question) {
$this->get('session')->getFlashBag()->add('danger', $this->get('translator')->trans('objectNotFound'));
return $this->redirect($this->generateUrl('app_question_list'));
}
$form = $this->createForm($this->get('form.type.question'), $question, array())->add('save', 'submit', array('label' => 'save', 'translation_domain' => 'messages', 'attr' => array('class' => 'btn btn-primary')));
$form->handleRequest($request);
if ($form->isValid()) {
// dump($question->getChildren()); // This is not empty. In this array are the selected childs.
$em->persist($question);
$em->flush();
}
}
更改您的实体方法:
public function addChild(Question $children)
{
$this->children[] = $children;
$children->setParent($this);
return $this;
}
我创建了一个带有自引用的实体。我的实体看起来像这样:
class Question
{
/**
* @ORM\OneToMany(targetEntity="Question", mappedBy="parent")
**/
private $children;
/**
* @ORM\ManyToOne(targetEntity="Question", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
**/
private $parent;
}
然后我创建了一个表单来编辑问题。使用此表格,我可以将许多孩子添加到一个问题中。在我 post 这张表格之后,我将把孩子们留到 parent Object。但是 parent 的孩子的持久化失败了,数据库中没有任何反应。
public function manageDependencyAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$question = $em->getRepository('AppMyBundle:Question')->find($id);
if (!$question) {
$this->get('session')->getFlashBag()->add('danger', $this->get('translator')->trans('objectNotFound'));
return $this->redirect($this->generateUrl('app_question_list'));
}
$form = $this->createForm($this->get('form.type.question'), $question, array())->add('save', 'submit', array('label' => 'save', 'translation_domain' => 'messages', 'attr' => array('class' => 'btn btn-primary')));
$form->handleRequest($request);
if ($form->isValid()) {
// dump($question->getChildren()); // This is not empty. In this array are the selected childs.
$em->persist($question);
$em->flush();
}
}
更改您的实体方法:
public function addChild(Question $children)
{
$this->children[] = $children;
$children->setParent($this);
return $this;
}