在我的一个存储库中获得了这个 QueryBuilder。
$query = $em->createQueryBuilder('d')
->select('d, i, u, SUM(CASE WHEN t.user = :userId THEN 1 ELSE 0 END) as myTickets')
->leftJoin('d.item','i')
->leftJoin('d.users','u')
->leftJoin('d.tickets','t')
->where('d.active = 1')
->andWhere('d.state = 1')
->setParameter('userId',$user->getId())
->orderBy('d.dateFinish', 'ASC');
当我执行代码时,MySQL 抛出这个错误。
Key "premium" for array with keys "0, myTickets" does not exist
“premium”是“d”的一个字段。
如何使用自定义 SUM 接收字段?
最佳答案
由于您在查询中使用聚合函数,因此您会得到所谓的混合结果
。混合结果通常会将使用 FROM
子句获取的对象返回为零索引 [0]
。结果的其余部分将根据您为自定义字段设置的别名进行填充。
$result[0]
将返回您要访问的对象。
$result['myTickets']
将返回聚合函数的结果。在本例中,它是一个 SUM
。
引用自文档:
SELECT u, UPPER(u.name) nameUpper FROM MyProject\Model\User u
This query makes use of the UPPER DQL function that returns a scalar value and because there is now a scalar value in the SELECT clause, we get a mixed result.
Conventions for mixed results are as follows:
The object fetched in the FROM clause is always positioned with the key ‘0’.
Every scalar without a name is numbered in the order given in the query, starting with 1.
Every aliased scalar is given with its alias-name as the key. The case of the name is kept.
If several objects are fetched from the FROM clause they alternate every row.
您可以阅读有关此主题的更多信息 here.
关于mysql - Symfony2 多对多与 COUNT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31294574/