views:

866

answers:

5

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

+4  A: 

You're right, it seems that you cannot use DISTINCT with list. Since you don't need id but only the names, you can use find all like above and then $first_names = Set::extract($first_names, '/Person/first_name');. That will give you a array with distinct first names.

Marko
Not only did this work perfectly for the list but I have used set commands in other places also. Thank you for sharing about this powerful library!
Frank Luke
me too - thanks very much for sharing
Tomba
+1  A: 

Yes the problem is that you are using a listing which designed for a id / value output. You probably will have to do a find('all') and then build the list yourself.

PetersenDidIt
+1  A: 

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

Muthukumaran
A: 

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'));
Kielanas
A: 

the way "Kielanas" told works just great! it's very helpful, thanks a lot!:)

A.I.