Skip to content Skip to sidebar Skip to footer

Cakephp: Limit Fields Associated With A Model

I have several fields in some of my database tables that my CakePHP models never need to retrieve. Is there some way to set a default set of fields to fetch at the model level? For

Solution 1:

CakePHP does not offer what you describe at the Model level out of the box. That is to say there is no Model property of defaultFields that is used on every find()

As you noted, you could specify this at the association level by setting the fields property. However, this would only work when you were retrieving the Model across one of these relationships.

In the end, you're going to be setting this in your find(). You could minimize repeating yourself by adding a property to your model like so:

var$defaultFields = array('Model.field1', 'Model.field2', ...);

Then in your find():

$this->Model->find('fields' => $this->Model->defaultFields, ...);

This has obvious limitations, but at least provides some encapsulation and therefore flexibility.

Note: A more invasive approach could use beforeFind();. In which case you would not need to adjust every find(). But your mileage may vary based on your usage.

Post a Comment for "Cakephp: Limit Fields Associated With A Model"