我正在尝试从数据库中获取一些具有内容计数(与任务相关)的任务,以及具有答案数(与任务相关)的任务对象(与任务相关)。 所以我使用标量作为计数,这很好,但是我无法通过分配来获得一个count_of_answers ...
在这里,如果我的实体关系:
class Task
{
/**
* @ORM\OneToMany(targetEntity="App\Entity\Assignment", mappedBy="task", orphanRemoval=true)
*/
private $assignments;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Content", mappedBy="task", orphanRemoval=true)
*/
private $contents;
}
class Content
{
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Task", inversedBy="contents")
* @ORM\JoinColumn(nullable=false)
*/
private $task;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Answer", mappedBy="content", orphanRemoval=true)
*/
private $answers;
}
class Assignment
{
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Task", inversedBy="assignments")
* @ORM\JoinColumn(nullable=false)
*/
private $task;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Answer", mappedBy="assignment", orphanRemoval=true)
*/
private $answers;
}
class Answer
{
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Content", inversedBy="answers")
* @ORM\JoinColumn(nullable=false)
*/
private $content;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Assignment", inversedBy="answers")
* @ORM\JoinColumn(nullable=false)
*/
private $assignment;
}
我想输入一个查询(我认为这样做可以避免在循环中查询):
Array [[
Task1{
properties,
assignments [
Assignment1{
properties,
count_of_answers
},
Assignment2{
properties,
count_of_answers
},...
]
},
count_of_contents
],
[
Task2{},
count_of_contents
],...
]
所以我在任务存储库中尝试了此查询:
$r = $this->createQueryBuilder('t')
->innerJoin('t.assignments', 'a')
->addSelect('a')
->innerJoin('t.contents', 'c')
->addSelect('COUNT(DISTINCT c.id) AS count_of_contents')
->leftJoin('a.answers', 'an')
->addSelect('COUNT(DISTINCT an.id) AS count_of_answers')
->groupBy('a.id')
->getQuery()
->getResult();
但是它给出了类似的内容:
Array[[
Task1{}
count_of_contents,
count_of_answers
],
Task2{}
count_of_contents,
count_of_answers
]]
能请你帮忙吗?
也许我应该在子查询中使用DQL,但是我很害怕在sql方面失去性能。我认为获取的数据很好(当我尝试sql查询时,确实有一个count_of_answers按分配),但是水化没有正确映射,我只获得了与任务关联的最后一个count_of_answers而不是分配。