在CakePHP查找函数中使用DISTINCT

Fra*_*uke 13 cakephp distinct find cakephp-1.2

我正在写一个CakePHP 1.2应用程序.我有一个人员列表,我希望用户能够在不同的字段上进行过滤.对于每个可过滤的字段,我有一个下拉列表.选择过滤器组合,单击过滤器,页面仅显示匹配的记录.

在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);
Run Code Online (Sandbox Code Playgroud)

(状态= 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')
));
Run Code Online (Sandbox Code Playgroud)

这给了我一个像这样的SQL错误:

Query: SELECT `Person`.`id`, DISTINCT `Person`.` first_name` FROM `people` AS `Person`   WHERE `Person`.`status` = 1   ORDER BY `Person`.`first_name` ASC
Run Code Online (Sandbox Code Playgroud)

问题很明显.该框架将Person.id添加到查询中.我怀疑这来自使用'list'.

单击过滤器按钮时,我将使用选定的过滤器创建SQL语句.我不需要is字段,但无法摆脱它.

谢谢Frank Luke

小智 24

尝试使用'group by',它的作用是完美的:

$first_names = $this->Person->find('list', array(
  'fields'=>'first_name',
   'order'=>'Person.first_name ASC',
   'conditions'=> array('Person.status'=>'1'),
   'group' => 'first_name'));
Run Code Online (Sandbox Code Playgroud)

  • 这有效,但会产生意想不到的后果,即按 first_name 对列表进行排序,这可能是不可取的。 (2认同)

Mar*_*rko 19

你说得对,看来你不能用DISTINCTlist.由于您不需要id但只需要名称,您可以find all像上面那样使用$first_names = Set::extract($first_names, '/Person/first_name');.这将为您提供一个具有不同名字的数组.

  • @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). (2认同)

Daw*_*jee 6

以下是我在 CakePHP 3.x 中的做法:

     $query = $this->MyTables->find('all');
     $result = $query->distinct()->toArray();
Run Code Online (Sandbox Code Playgroud)


小智 5

你可以试试这个.这里将Person id作为键,因此没有重复输入的机会.

    $first_names = $this->Person->find('list', array(
    'fields' => array('id','first_name'),
    'conditions' => array('Person.status' => '1'),
   ));
    $this->set('first_names', $first_names);
Run Code Online (Sandbox Code Playgroud)