问题
I want to access a query result in twig as a whole object. In the query however, I want to select just several fields from the tables + count. In my example I have a company, which is owned by an owner and has several employees. I want to create a query, which gives me a list of companies ordered by count of their employees.
$qb = $this->createQueryBuilder('c');
$qb->select('count(e.id), partial c.{id, name}, partial o.{id, name}');
$qb->leftJoin('c.employees', 'e');
$qb->innerJoin('c.owner', 'o');
$qb->groupBy('c.id');
The query works fine, however I get an error, when I want to access other objects liked with normaly in the company entity (there is an collection of image entities, and each image entity contains the path to the image). The query does not load the whole company entity with its dependencies... I cannot acces the "firstImage" method, which returns the first image from the collection. I get this error
Key "firstImage" for array with keys "0, 1" does not exist in MyBundle:List:results.html.twig at line 6
Note that leaving out the "employees count" makes it whole work.
$qb = $this->createQueryBuilder('c');
$qb->select('partial c.{id, name}, partial o.{id, name}');
$qb->leftJoin('c.employees', 'e');
$qb->innerJoin('c.owner', 'o');
$qb->groupBy('c.id');
回答1:
Your object will be the first element of result array and the count() value will be the second. You can access to object properties and methods in twig by the following way:
{{ object[0].firstImage }}
{{ object[0].name }}
And the count of employees can be accessed as:
{{ object[1] }}
Also you may define the name for your count() value in the query
$qb->select('count(e.id) AS empQty, partial c.{id, name}, partial o.{id, name}');
and then you can access this value in twig as:
{{ object['empQty'] }}
来源:https://stackoverflow.com/questions/22574618/how-can-i-select-countfield-and-still-get-an-object-with-createquerybuilder