1

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 Answer 1

4

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'] }}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.