Persisting object with relationship, database not

2019-08-29 20:10发布

问题:

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