04 June, 2011

Override CakePHP model's find method

By default CakePHP's find method of model allows us to use four types of find, viz
"all", "first", "count" and "list", but in some cases we need to find something using
some other type, like find all the pending blog posts of a user.

In such case we can just override the cakePHP's model find method in our model to suit our needs. Lets say we have a model named Post for posts table in database. So, our overridden model would look like:

class Post extends AppModel {
//relationships
var $belongsTo = array('User');

function find($type, $queryData = array()) {
switch($type) {
case "pending":
//field is_published is tinyint with value 1 OR 0 for published or pending respectively
$pending = $this->find('all', array('conditions'=>array('Post.is_published' => 0), 'contain' => array('User')));
return $pending;
break;
default:
//call the default find method with all related parameters
return parent::find($type, $queryData);
}
}
}
?>

So now in function of our controller, we can use this as:

//get the id of logged in user
$userId = $this->Auth->user('id');
$pendingPosts = $this->Post->find('pending', array('user_id' => $userId));
?>

And thats it.