JD *_*cks 6 cakephp group-by count cakephp-1.3
我知道这里有一些类似的问题,但它们都是关于何时使用
Model->find('all');
Run Code Online (Sandbox Code Playgroud)
但那不是我正在做的事情,我在做:
Model->find('list');
Run Code Online (Sandbox Code Playgroud)
这是什么使这个工作和不工作之间的区别.
鉴于一组产品,我想找到该组中的所有品牌以及每个品牌的数量.
听起来很简单,这就是我所做的:
$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);
Run Code Online (Sandbox Code Playgroud)
在这里我告诉它给我一个数组,其中键是Product.brand
值和值COUNT(Product.brand)
我得到这个:
Array
(
[Brand A] =>
[Brand B] =>
[Brand C] =>
)
Run Code Online (Sandbox Code Playgroud)
当我被期待时:
Array
(
[Brand A] => 534
[Brand B] => 243
[Brand C] => 172
)
Run Code Online (Sandbox Code Playgroud)
它可以工作,如果我做所有而不是列表,它只是给我一个更复杂的数组来钻取.我很好用所有,我只是想先看看它是否有理由不在列表中工作?
lxa*_*lxa 12
简要回顾:find('list')存在别名字段问题(因此聚合函数COUNT()
等等),所以你应该使用CakePHP的1.3代替.对于CakePHP 1.2,使用了一个装置.
详细:最有可能的问题在于你的问题
COUNT(`Product.brand`) AS brand_count
Run Code Online (Sandbox Code Playgroud)
由于find('list')
不
Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath'])
Run Code Online (Sandbox Code Playgroud)
在查询的结果,$lst['valuePath']
将在哪里
"{n}.COUNT(`Product`.`brand`) AS brand_count"
Run Code Online (Sandbox Code Playgroud)
而在结果中它实际上是"{n}.Product.brand_count"
- 不排队.
尝试将COUNT()设为虚拟字段.
即:
//model
var $virtualFields = array(
'brand_count' => 'COUNT(Product.brand)'
);
//controller
$fields = array('Product.brand','Product.brand_count');
Run Code Online (Sandbox Code Playgroud)