I have a query that fetches some information from a table AND the count of related objects from another table. I have trouble expressing it in DQL, so it will return a flat array.
This example fetches the school, the name of the school and the number of students of each school:
$qB = $this->createQueryBuilder('school')
$qB->leftJoin('school.students', 'students');
$qB->select([
'partial school.{id, name}',
'count(students) AS number_students',
]);
$qB->groupBy('school');
$qB->getQuery()->getResult();
I am expecting it to return:
[
[id => 1, 'name' => 'School A', 'number_students' => 5],
[id => 2, 'name' => 'School B', 'number_students' => 3],
]
But I end up getting this:
[
[0 => [id => 1, 'name' => 'School A'], 'number_students' => 5],
[0 => [id => 2, 'name' => 'School B'], 'number_students' => 3],
]
As a workaround it is possible to use $qB->getQuery()->getScalarResult()
, but that then converts the variable names (e.g. The entity variable name schoolName
is then converted to the column title in the database school_name
), which means I would have to remap the fields again.
It is perhaps related in the way Doctrine treats entities. Here is the school entity of the example:
class School {
protected $id;
protected $name;
protected $students;
}