如何选择计数(字段)并仍然使用 createQueryBuilder 获取对象 [英] How can I select count(field) and still get an object with createQueryBuilder

查看:53
本文介绍了如何选择计数(字段)并仍然使用 createQueryBuilder 获取对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 twig 中的查询结果作为一个整体来访问.但是,在查询中,我只想从表 + 计数 中选择几个字段.在我的示例中,我有一家公司,该公司归所有者所有,并且有几名员工.我想创建一个查询,它为我提供按员工人数排序的公司列表.

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');

查询工作正常,但是当我想访问公司实体中喜欢的其他对象时出现错误(有一组图像实体,每个图像实体都包含图像的路径).查询不会加载整个公司实体及其依赖项...我无法访问firstImage"方法,该方法返回集合中的第一个图像.我收到此错误

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

键为0, 1"的数组的键firstImage"不存在于MyBundle:List:results.html.twig 在第 6 行

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');

推荐答案

您的对象将是结果数组的第一个元素,而 count() 值将是第二个.您可以通过以下方式访问 twig 中的对象属性和方法:

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] }}

您也可以在查询中定义 count() 值的名称

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}');

然后你可以在twig中访问这个值:

and then you can access this value in twig as:

{{ object['empQty'] }}

这篇关于如何选择计数(字段)并仍然使用 createQueryBuilder 获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆