原则2:水合键值数组 [英] Doctrine 2: Hydrate key-value array
问题描述
为什么该查询不起作用?
Why this query doesn't work?
$query = $this->_em->createQuery('
SELECT
COUNT(p) AS products_count
FROM
Application\Entity\Category c
INDEX BY c.id
LEFT JOIN c.products p
GROUP BY
c.id
');
$rows = $query->getSingleScalarResult();
我希望得到的结果为: category_id => products_count数组,但是会抛出一个学说\ORM\NonUniqueResultException,没有任何消息。
I expected to get the result as: "category_id => products_count" array, but it throws an Doctrine\ORM\NonUniqueResultException without any message.
推荐答案
如果您 COUNT
查询中 GROUPED
的行,它将返回多个结果以及每个组的计数。对于您来说,您将获得每个类别
的计数。
If you COUNT
the rows in a query that is GROUPED
, it will return multiple results with the count for each group. In your case, you will get the counts for each Category
.
如果尝试 getSingleScalarResult()
对具有多个条目的结果,将产生 Doctrine\ORM\NonUniqueResultException
。相反,您应该使用 getScalarResult()
并遍历条目。
If you try to getSingleScalarResult()
on a result which has more than one entries, it will produce a Doctrine\ORM\NonUniqueResultException
. Instead, you should use getScalarResult()
and iterate through the entries.
编辑:
要将结果转换为 array( category_id => products_count_value)
的形式,可以使用以下代码:
To transform the results to the form array("category_id" => "products_count_value")
, you can use the following code:
$output = array();
foreach ($rows as $category, $values) {
$output[$category] = $values['products_count'];
}
$ output
应该现在包含您想要的值。
$output
should now contain the values the way you want them.
这篇关于原则2:水合键值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!