Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: How to write a find() query that excludes one field in the resultset?

Is there a way to write a CakePHP query to return all fields (columns) except one via find()? Or do I need to use the fields parameter and actually list all the fields, except the excluded field?

For example, if I have a database table (model), Company, with these fields:

id
name
street
city
state
zip
phone

Normally, $this->Company->find('all') would return all the fields. I want to exclude the phone field from the resultset.

like image 279
Stephen Avatar asked Feb 16 '23 13:02

Stephen


2 Answers

$fields = array_keys($this->Company->getColumnTypes());
$key = array_search('phone', $fields);
unset($fields[$key]);
$this->Company->find('all', array('fields' => $fields));

For more info, please have a look at http://book.cakephp.org/2.0/en/models/additional-methods-and-properties.html#model-getcolumntypes

like image 118
Anil kumar Avatar answered May 19 '23 13:05

Anil kumar


I can think of a couple ways to do this

  1. Write out all the fields you want to include in the fields parameter. As mentioned in the comment, you can use $this->Company->schema to get all the fields programmatically rather than writing them out.

  2. Unset the field you don't want after you get the data. You can do this in the model's afterFind function too.

like image 20
Kai Avatar answered May 19 '23 13:05

Kai