»
S
I
D
E
B
A
R
«
Using DISTINCT in a CakePHP find function
November 11th, 2009 by wood

Hello,

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. Choose the filter combination, click filter, and the page shows only the records that match.

In people_controller, I have this bit of code:

$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);

(Status = 1 because I am using a soft delete.)

That creates an ordered list of all first_names. But duplicates are in there.

Digging around in the Cookbook, I found an example using the DISTINCT keyword and modified my code to use it.

$first_names = $this->Person->find('list', array(
    'fields'=>'DISTINCT first_name',
    'order'=>'Person.first_name ASC',
    'conditions'=> array('Person.status'=>'1')
));

This gives me an SQL error like this:

Query: SELECT `Person`.`id`, DISTINCT `Person`.` first_name` FROM `people` AS `Person`   WHERE `Person`.`status` = 1   ORDER BY `Person`.`first_name` ASC

The problem is obvious. The framework is adding Person.id to the query. I suspect this comes from using 'list'.

I will use the selected filter to create an SQL statement when the filter button is clicked. I don't need the is field, but can't get rid of it.

Thank you, Frank Luke


One Response  
  • Hazem writes:
    January 13th, 2010 at 11:24 am

    Unfortunately ‘list’ is really the problem. To do this you have to find it with ‘all’ instead of list then iterate the results to get the selected field in a new array just like this

    {{{
    $db_first_names = $this->Person->find(’all’, array(
    ‘fields’=>’DISTINCT first_name’,
    ‘order’=>’Person.first_name ASC’,
    ‘conditions’=> array(’Person.status’=>’1′)
    ));

    $first_names = array();
    foreach($db_first_names as $first_name){
    $first_names[] = $first_name['Person']['first_name'];
    }
    }}}

    The preferred method is to create a function in the model that does the same functionality.


Leave a Reply

»  Substance: PHP Frameworks   »  SiteMap