Using DISTINCT in a CakePHP find function

后端 未结 12 1889
情歌与酒
情歌与酒 2020-12-06 05:54

I am writing a CakePHP 1.2 app. I have a list of people that I want the user to be able to filter on different fields. For each filterable field, I have a drop down list.

相关标签:
12条回答
  • 2020-12-06 06:15

    Just group by the fields that you want to get distinct.. or use Set::extract() and then array_unique()

    0 讨论(0)
  • 2020-12-06 06:21

    Here's how I did it in CakePHP 3.x:

         $query = $this->MyTables->find('all');
         $result = $query->distinct()->toArray();
    
    0 讨论(0)
  • 2020-12-06 06:22

    Yes I also tried to fetch unique results with 'list' but its not working. Then I fixed the problem by using 'all'.

    0 讨论(0)
  • 2020-12-06 06:23

    Using SQL grouping will also produce a distinct list. Not sure of the negative consequences if any, but it seems to work fine for me.

    $first_names = $this->Person->find('list', array(
        'fields' => 'first_name',
        'order' => 'first_name',
        'group' => 'first_name',
        'conditions' => array('Person.status' => '1'),
    ));
    $this->set('first_names', $first_names);
    
    0 讨论(0)
  • 2020-12-06 06:25

    I know it is a question for CakePHP 1.2, but I was searching for that too with CakePHP version 3. And in this version there is a method to form the Query into a distinct one:

    $first_names = $this->Persons->find(
        'list',
        [
            'fields'=> ['name']
        ]
    )
      ->distinct();
    ;
    

    This will generate a sql query like this:

    SELECT DISTINCT Persons.name AS `Persons__name` FROM persons Persons
    

    But the distinct method is a bit mightier than just inserting DISTINCT in the query.

    If you want to just distinct the result on one field, so just throwing away a row with a duplicated name, you can also use the distinct method with an array of the fields as parameter:

    $first_names = $this->Persons->find(
        'list',
        [
            'fields'=> ['id', 'name'] //it also works if the field isn't in the selection
        ]
    )
      ->distinct(['name']); //when you use more tables in the query, use: 'Persons.name'
    ;
    

    This will general a sql query like this (for sure it is a group query):

    SELECT DISTINCT
        Persons.id AS `Persons__id`, Persons.name AS `Persons__name`
    FROM persons Persons
    GROUP BY name #respectively Persons.name
    

    Hope I will help some for CakePHP 3. :)

    0 讨论(0)
  • 2020-12-06 06:29

    Try to use 'group by', it works perfectry:

    $first_names = $this->Person->find('list', array(
      'fields'=>'first_name',
       'order'=>'Person.first_name ASC',
       'conditions'=> array('Person.status'=>'1'),
       'group' => 'first_name'));
    
    0 讨论(0)
提交回复
热议问题