CakePHP GROUP 和 COUNT 个项目在列表中返回
我知道这里有一些类似的问题,但它们都是关于使用时的问题
Model->find('all');
,但这不是我正在做的事情,我正在做的事情:
Model->find('list');
这就是工作和不工作之间的区别。
给定一组产品,我想找到该组中的所有品牌以及每个品牌的数量。
听起来很简单,这就是我所做的:
$fields = array('Product.brand','COUNT(`Product`.`brand`) AS brand_count')
$brand_data = $this->Product->find('list',array(
'fields'=>$fields,
'conditions'=>$conditions,
'recursive'=>0,
'group' => 'Product.brand'
));
debug($brand_data);
在此我告诉它给我一个数组,其中键为 Product.brand
,值为 COUNT(Product.brand)
code>
我得到这个:
Array
(
[Brand A] =>
[Brand B] =>
[Brand C] =>
)
当我期望这个:
Array
(
[Brand A] => 534
[Brand B] => 243
[Brand C] => 172
)
如果我执行 all 而不是 list ,它就会起作用,它只会给我一个更复杂的数组来钻取。我可以使用all,我只是首先想看看是否有原因导致它在list中不起作用?
I know there are some similar quesiton like this on here but they are all about when using
Model->find('all');
But thats not what I am doing, I am doing:
Model->find('list');
Which is whats making the difference between this working and not working.
Given a group of Products I want to find all the brands in that group and how many of each brand.
Sounds simple enough, here is what I did:
$fields = array('Product.brand','COUNT(`Product`.`brand`) AS brand_count')
$brand_data = $this->Product->find('list',array(
'fields'=>$fields,
'conditions'=>$conditions,
'recursive'=>0,
'group' => 'Product.brand'
));
debug($brand_data);
In this I am telling it to give me an array where the Keys are Product.brand
and the values are COUNT(Product.brand)
I am getting this:
Array
(
[Brand A] =>
[Brand B] =>
[Brand C] =>
)
When I am expected this:
Array
(
[Brand A] => 534
[Brand B] => 243
[Brand C] => 172
)
It works if I do all instead of list though, it just gives me a much more complicated array to drill through. I am fine using all, I just first wanted to see if there was a reason why its not working in list?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简要回顾:find('list') 在别名字段方面存在问题(因此聚合函数如
COUNT()
等),因此您应该使用 CakePHP 的 1.3。对于 CakePHP 1.2 使用,有 一个装置。详细:
最有可能的问题在于您的
because
find('list')
doeson results of query,其中
$lst['valuePath']
是,而在结果中它实际上是
“{n}.Product.brand_count”
- 未排队。尝试将 COUNT() 设置为虚拟字段。
IE:
Brief recap: find('list') has problems with aliased fields (and therefore aggregate functions like
COUNT()
etc.), so you should use CakePHP's 1.3 instead. For CakePHP 1.2 uses there's a contraption.Detailed:
Most likely problem lies in your
Because
find('list')
doeson results of query, where
$lst['valuePath']
would bewhile in results it would be actually
"{n}.Product.brand_count"
- doesn't line up.Try making your COUNT() a virtual field.
I.e.:
在 Paginator 的控制器中,您可以像这样使用:
In controller in Paginator you can use like this: