php - Doctrine ORM ManyToOne Inverse 不起作用
问题描述
我有一个双向多对一对多关系,只在一个方向上工作,有人可以帮忙。为了清楚起见,我试图将示例简化为最少的代码。
Question 实体可以有许多 Answer 实体。
问题实体
class CwEmployeeQuestion
{
public function __construct()
{
$this->cw_employee_answers = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* @ORM\Column(type="guid")
* @ORM\Id
* @ORM\GeneratedValue(strategy="UUID")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="Fitchek\Entity\Corporate\CwEmployeeAnswer", mappedBy="cw_employee_question")
*/
protected $cw_employee_answers;
/**
* Get CwEmployeeAnswer
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getCwEmployeeAnswer()
{
return $this->cw_employee_answers;
}
}
回答实体
class CwEmployeeAnswer
{
/**
* @ORM\Column(type="guid")
* @ORM\Id
* @ORM\GeneratedValue(strategy="UUID")
*/
protected $id;
/**
* Many CwEmployeeAnswer have One CwEmployeeQuestion.
*
* @var \Fitchek\Entity\Corporate\CwEmployeeQuestion $cw_employee_question
*
* @ORM\ManyToOne(targetEntity="Fitchek\Entity\Corporate\CwEmployeeQuestion", inversedBy="cw_employee_answer")
* @ORM\JoinColumn(name="cw_employee_question", referencedColumnName="id")
*/
protected $cw_employee_question;
/**
* Set $cw_employee_question
*
* @param \Fitchek\Entity\Corporate\CwEmployeeQuestion $cw_employee_question
* @return CwEmployeeAnswer
*/
public function setCwEmployeeQuestion(?\Fitchek\Entity\Corporate\CwEmployeeQuestion $cw_employee_question = null): self
{
$this->cw_employee_question = $cw_employee_question;
return $this;
}
/**
* Get $cw_employee_question
*
* @return \Fitchek\Entity\Corporate\CwEmployeeQuestion
*/
public function getCwEmployeeQuestion(): ?CwEmployeeQuestion
{
return $this->cw_employee_question;
}
/**
*
* {@inheritdoc}
*
* @param JSON $json, the request JSON to create a new CwEmployeeAnswer
* @return CwEmployeeAnswer the newly created CwEmployeeAnswer
*/
public function createFromData($json, $cw_employee_question = null)
{
$this->setCwEmployeeQuestion($cw_employee_question);
return $this;
}
}
当我尝试方向答案-> 问题时,它工作正常,并返回给我一个答案列表,其中包含作为 JSON 的一部分的相关问题。例如:
[
{ "id": 1
"name": "answer 1",
"question" : {
"name": "question 1"
}
}
...
]
但是,当查询另一个方向以获取所有问题及其答案作为返回 JSON 的一部分时,问题数组将返回为 null。例如:
[
{ "id": 1
"name": "question 1",
"answers": null
}
...
]
当我想看到的是:
[
{ "id": 1
"name": "question 1",
"answers" : [
{
"name": "answer 1"
},
{
"name": "answer 2"
}
...
]
}
...
]
解决方案
好像没问题。可能只是一个错字。尝试使用inversedBy="cw_employee_answers"
(plural as $cw_employee_answers) 而不是inversedBy="cw_employee_answer"
它应该可以工作。
推荐阅读
- javascript - Vue js - 在同一级别的两个组件内传递数据
- javascript - 带按键暂停的 setTimeout 函数重载
- jquery - select2 - 如何预选从 AJAX 远程源接收数据的多个选项
- java - 如何将嵌套的 for 循环转换为递归
- r - 如何使用ggplot根据列的值更改点的大小?
- php - ajax 数据工作和结果来到#div1 但在 islenendata.php 结果没有出现
- bash - bash 中的 awk 语法错误。在 zsh 中运行良好
- ruby-on-rails - rails inline_svg 与carrierwave上传的文件
- scala - 运算符 ++= 在 Scala 中的一对上
- c - 通过覆盖其元素在 C 中删除 2D 数组的列