持久对象与关系,数据库不更新 [英] Persisting object with relationship, database not updating

查看:104
本文介绍了持久对象与关系,数据库不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个关系关系实体 OneToMany

I have 2 entities with relationship OneToMany.

实体问题:

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

实体答案:

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

这里我尝试坚持:

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

当我运行此代码时,数据库中的所有更新除了答案表中的外键外,code> question_id 为null。

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 ?

推荐答案

这必须是五大最受欢迎的教条2问题之一。但是我太懒了,要查找一个链接。

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

这篇关于持久对象与关系,数据库不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆