OneToMany关系为NULL作为外键?

问题描述 投票:1回答:1

Preamble


我正试图POST(在Postgresql数据库中插入)一个JSON格式的实体转换成PHP对象,这要归功于FOSRestBundleJMSSerializerBundle的路由。这个实体看起来像这样:

**Vote** : OneToOne Bidirectional : **Question** : OneToMany Bidirectional : Answer

这里的JSON有效负载:

{
  "title": "string",
  "description": "string",
  "question": {
    "id": 0,
    "title": "string",
    "description": "string",
    "answers": [
      {
        "title": "string",
        "description": "string"
      },
      {
        "title": "First answer ?",
        "description": "string"
      }
    ]
  }
}

问题


当它插入投票时,问题字段中的vote_id以及答案中的question_id为空。

当我从我的路线获得有效载荷时,它变成了一个对象,其中fos_rest.request_body就是动作:

    public function postVoteAction(Vote $vote, ConstraintViolationList $violations)
    {
        if (count($violations)) {
            return $this->view($violations, Response::HTTP_BAD_REQUEST);
        }
        $em = $this->getDoctrine()->getManager();
        $vote->setOwner($this->getUser());
        $em->persist($vote);
        $em->flush();
        return $vote;
    }

我确实得到了一个带有我的问题和答案的投票对象,但当它被插入数据库时​​,因为前面说的外键字段是NULL。

我已经做了什么


我调查了关系,看看是否存在实体cascade={"persist"}

// in vote
@ORM\OneToOne(targetEntity="Question", mappedBy="vote", cascade={"persist", "remove"})
private $question;

// in question
@ORM\OneToOne(targetEntity="Vote", inversedBy="question", cascade={"persist"})
@ORM\JoinColumn(name="vote_id", referencedColumnName="id")
private $vote;

@ORM\OneToMany(targetEntity="Answer", mappedBy="question", cascade={"persist", "remove"})
private $answers;

// in answer
@ORM\ManyToOne(targetEntity="Question", inversedBy="answers", cascade={"persist"})
@ORM\JoinColumn(name="question_id", referencedColumnName="id")
private $question;

我使用php bin\console make:entity --regenerate获得所有的吸气剂/安装者。我清理了数据库并重新生成了它。

回答


正如@yTko所说的那样,我忘了将引用放回到我的控制器中的对象中我认为它是由Doctrine用persist制作的,所以这里现在是我的工作代码:

public function postVoteAction(Vote $vote, ConstraintViolationList $violations)
{
    if (count($violations)) {
        return $this->view($violations, Response::HTTP_BAD_REQUEST);
    }

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

    $vote->setOwner($this->getUser());
    $question = $vote->getQuestion();
    $question->setVote($vote);
    foreach ($question->getAnswers() as $answer) {
        $answer->setQuestion($question);
    }
    $em->persist($vote);
    $em->flush();

    return $vote;
}
php postgresql symfony doctrine-orm fosrestbundle
1个回答
1
投票

我认为你只是忘了设置相关的投票和问题实例。

在您的控制器操作中,您有一个jms转换为json示例的投票对象。

因此,您需要通过调用某些setter来手动设置它们,如下所示:

$question = $vote->getQuestion();
$question->setVote($vote);

或者以这种方式修改你的二传手:

public function setQuestion(Question $question)
{
    $this->question = $question;
    $this->question->setVote($this);

    return $this;
}

我更喜欢第一种方式,因为setter只是用于设置具体值,而不是用于修改其他对象。

© www.soinside.com 2019 - 2024. All rights reserved.