Question

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 instance I retrieve some data from a third party designed database that has 50 fields per table, I use 5.

I know I can set limits on fields at the time of the find() query and at the time of any associations between models, but I was wondering if there was a model-level approach.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top