我正在编写一个CakePHP 1.2应用程序。我有一份我希望用户能够在不同字段上筛选的人员列表。对于每个可过滤的字段,我有一个下拉列表。选择过滤器组合,单击过滤器,页面只显示匹配的记录。在CakePHP查找函数中使用DISTINCT
在people_controller,我有这段代码:
$first_names = $this->Person->find('list', array(
'fields'=>'first_name',
'order'=>'Person.first_name ASC',
'conditions'=> array('Person.status'=>'1')
));
$this->set('first_names', $first_names);
(状态= 1,因为我用的是软删除。)
这造成所有first_names的有序列表。但重复在那里。
在Cookbook中挖掘,我找到了一个使用DISTINCT关键字并修改我的代码来使用它的例子。
$first_names = $this->Person->find('list', array(
'fields'=>'DISTINCT first_name',
'order'=>'Person.first_name ASC',
'conditions'=> array('Person.status'=>'1')
));
这给了我这样一个SQL错误:
Query: SELECT `Person`.`id`, DISTINCT `Person`.` first_name` FROM `people` AS `Person` WHERE `Person`.`status` = 1 ORDER BY `Person`.`first_name` ASC
的问题是显而易见的。该框架将Person.id添加到查询中。我怀疑这是来自使用'列表'。
我将使用选定的过滤器在单击过滤器按钮时创建SQL语句。我不需要这个领域,但不能摆脱它。
谢谢 弗兰克卢克
不仅没有这项工作非常的名单,但我已经在其他地方使用的命令集也。感谢您分享这个功能强大的图书馆! – 2009-11-20 17:14:45
我试过了,但我仍然在结果列表中找到重复项。 – paullb 2012-06-28 03:06:22
@paullb你可以使用['array_unique'](http://php.net/manual/en/function.array-unique.php)从提取的数组中删除重复项。当你在这个时候,看一下['Hash'类](http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html)(自CakePHP 2.2以来)将最终取代['Set'](http://book.cakephp.org/2.0/en/core-utility-libraries/set.html)。 – 2012-07-03 05:15:47