gpt4 book ai didi

mysql - Doctrine2 一对多关系反方不保存所属方 ID

转载 作者:行者123 更新时间:2023-11-29 20:16:29 26 4
gpt4 key购买 nike

我有 2 个实体:提交和投票。

提交实体:

  /**
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Votes", mappedBy="submission",cascade={"persist", "remove" })
* @ORM\JoinColumn(name="id", referencedColumnName="submission_id")
*/
protected $vote;

/**
* @return mixed
*/
public function getVote()
{
return $this->vote->toArray();
}

/**
* @param Votes $vote
* @return $this
*
*/
public function setVote(Votes $vote)
{
if (!$this->vote->contains($vote)) {
$this->vote->add($vote);
}
return $this;
}

投票实体:

  /**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Submission", inversedBy="id")
* @ORM\JoinColumn(name="submission_id", referencedColumnName="id", nullable=true)
*/
protected $submission;

/**
* @return mixed
*/
public function getSubmission()
{
return $this->submission;
}

/**
* @param mixed $submission
*/
public function setSubmission($submission)
{
$this->submission = $submission;
}

问题是,当我为之前选择的提交设置投票时:

$submission = $em->getRepository('AppBundle:Submission')->findOneById($submissionId);
$vote = new Votes();
$vote->setId($submission->getId());
$vote->setFeedback($judgeComment);
$vote->setScore($judgeScore);
$vote->setSubmission($submissionId);
$submission->setVote($vote);
$em->persist($submission);
$em->flush();

Vote table

submission_id 列始终为 NULL - 我不确定我做错了什么。我想在这里存储提交 ID,以了解这次投票的内容。

最佳答案

你不必在 Doctrine 中设置 id,而是在对象中设置 id,因为它是一个 ORM

$submission = $em->getRepository('AppBundle:Submission')->findOneById($submissionId);
$vote = new Votes();
$vote->setId($submission->getId()); // <--- Are you sure that you need this?
$vote->setFeedback($judgeComment);
$vote->setScore($judgeScore);
// $vote->setSubmission($submissionId); <--- ERROR!
$vote->setSubmission($submission) // <--- Check advice below
$submission->setVote($vote);
$em->persist($submission);
$em->flush();

如果我也可以在这里留下建议,请修改setVote如下

public function setVote(Votes $vote)
{
if (!$this->vote->contains($vote)) {
$this->vote->add($vote);
$vote->setSubmission($this);
}
return $this;
}

并且您将不再需要显式设置关联双方

我还注意到您的类名是复数(应该在域中是单数)并且 vote 属性在 submission 中是单数(应该是复数,因为它是一个集合;你有一个-to-Many注释。甚至setter也应该是一个adder 因为您不是设置而是添加投票)

关于mysql - Doctrine2 一对多关系反方不保存所属方 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39750018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com