Custom method for grabbing a row based on its id
Friday, August 14th 2009, 2:14am
Topics: Tutorials, CakePHP
Tags: Model, Data, Get, Grab, Row, Magic
Comments: 1
Permalink -
Tinylink
More times then none when working with a database, you need a general purpose method for grabbing fields from a row that matches an id. Cake has built in magic methods based on the table column that do just that, for example findById() or findBySlug(), but sometimes it grabs associated data that you do not want. Below is a basic method that you can place in your AppModel to grab a row based on its id, with optional parameters for restricting what fields to grab or what associations to contain.
With a little bit of editing, you can make it work for other fields other then id. You must also have containable listed in your behaviors for the 3rd argument to work. If you still aren't sure how to use this method, the following examples should help.
/**
* Grab a row and defined fields/containables
* @param int $id
* @param array $fields
* @param array $contain
* @return array
*/
function get($id, $fields = array(), $contain = false) {
if (empty($fields)) {
$fields = $this->alias .'.*';
} else {
foreach ($fields as $row => $field) {
$fields[$row] = $this->alias .'.'. $field;
}
}
return $this->find('first', array(
'conditions' => array($this->alias .'.id' => $id),
'fields' => $fields,
'contain' => $contain
));
}
With a little bit of editing, you can make it work for other fields other then id. You must also have containable listed in your behaviors for the 3rd argument to work. If you still aren't sure how to use this method, the following examples should help.
// Grab a basic row based on id
$user = $this->User->get($id);
// Grab a row and limit fields
$user = $this->User->get($id, array('id', 'username'));
// Grab a row, fields and associations
$user = $this->User->get($id, array('id', 'username'), array('Country', 'Profile'));
1 Comments
Sep 1st 2009, 00:48
method in the Model class that does the same as your custom method.