Persisting object with relationship, database not updating

大城市里の小女人 提交于 2019-12-13 04:47:42

问题


I have 2 entities with relationship OneToMany.

entity Question:

   /**
    * @ORM\OneToMany(targetEntity="Quiz\CoreBundle\Entity\Answer", mappedBy="question", cascade={"persist"})
    */
    private $answers;

entity answer:

/**
 * @ORM\ManyToOne(targetEntity="Quiz\CoreBundle\Entity\Question", inversedBy="answers")
 */
private $question;

Here I try to persist :

$em = $this->getDoctrine()->getManager();

            $question  = new Question();
            $answer = new Answer();
            $answer2 = new Answer();


            $answer->setAnswerText('Roterdam');
            $answer2->setAnswerText('Amsterdam')
                 ->SetCorrect(true);
            $question->setQuestionText('What\'s the capital of Netherlands? ');

            $question->addAnswer($answer);
            $question->addAnswer($answer2);

            $em->persist($question);
            $em->flush();

When I run this code everything updates in the db except the foreign key in answer table, the question_id is null.

Any idea what am I doing wrong ?


回答1:


This has got to be one of the top five most popular Doctrine 2 questions. But I'm too lazy to look up one to link to.

Ask yourself how the answer knows to which question does it belong? Where is the link at the object level?

class Question
{
    function addAnswer($answer)
    {
        $this->answers[] = $answer;
        $answer->setQuestion($this);
    }
}


来源:https://stackoverflow.com/questions/28257869/persisting-object-with-relationship-database-not-updating

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!