持久的自引用实体不起作用

时间:2015-03-25 06:17:03

标签: symfony

我创建了一个具有自引用功能的实体。我的实体看起来像这样:

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;
}

我创建了一个表单来编辑问题。使用此表单,我可以在问题中添加许多孩子。发布此表单后,我将保存子对象的父对象。但是父母的子女的持续失败,数据库中没有任何事情发生。

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();
    }
}

1 个答案:

答案 0 :(得分:3)

更改您的实体方法:

public function addChild(Question $children)
{
    $this->children[] = $children;
    $children->setParent($this);

    return $this;
}