我知道这里有一些类似的问题,但它们都是关于使用时的
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)
我得到这个:
Array
(
[Brand A] =>
[Brand B] =>
[Brand C] =>
)
当我期待这个时:
Array
(
[Brand A] => 534
[Brand B] => 243
[Brand C] => 172
)
如果我这样做就有效all代替list不过,它只是给了我一个更复杂的数组来钻取。我很好用all,我首先想看看是否有原因导致它无法在list?
简要回顾: find('list') 对于别名字段存在问题(因此聚合函数如COUNT()
等),所以你应该使用 CakePHP 的 1.3。对于 CakePHP 1.2 的使用,有一个装置 http://nuts-and-bolts-of-cakephp.com/2008/09/04/findlist-with-three-or-combined-fields/.
Detailed:
最有可能的问题在于你的
COUNT(`Product.brand`) AS brand_count
Because find('list')
does
Set::combine($results, $lst['keyPath'], $lst['valuePath'], $lst['groupPath'])
查询结果,其中$lst['valuePath']
将会
"{n}.COUNT(`Product`.`brand`) AS brand_count"
而结果实际上是"{n}.Product.brand_count"
- 不排队。
尝试将 COUNT() 设置为虚拟字段。
I.e.:
//model
var $virtualFields = array(
'brand_count' => 'COUNT(Product.brand)'
);
//controller
$fields = array('Product.brand','Product.brand_count');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)