I am new to CakePHP, and while I really enjoy the ease of being able to just select a model and all its associated models, I am trying to figure out if there is an easier way to not just have all the fields selected from each model.
For example, instead of just automatically selecting all fields when I grab the model data, and without having to laboriously specify a fields=>array(...) every time, is there so开发者_如何学编程me way I can specify which fields are selected by default?
You can also create your own find method in the model:
function findSelected($options = array()) {
$options['fields'] = array('id','name');
return $this->find('all', $options);
}
in controller:
$this->Model->findSelected(array('order' => 'id ASC'));
Even nicer to merge the options array in the findSelected method, then you can even provide additional fields on the fly.
yes, you can check in beforeFind of that model if the 'fields' key is set, if not, you can set it there. But I would say, other than making the debug looks neater, there's almost no performance gain in doing that. And it's one more thing to keep in mind if you have to make changes to the model.
You want to have a look at the Containable behaviour - http://book.cakephp.org/view/1323/Containable
It's very well documented, but to give you a brief overview
$this->Article->find('all', array(
'contain' => array(
'Author.name',
'Category' => array(
'name',
'icon'
)
)
));
would return all your Articles data, along with just the three other fields.
I have Containable added to my app_model definition because I use it on all but the simplest of finds.
精彩评论