Question for CakePHP newbies: How to add a non-database attribute to a model?

I want to create a model in which there are SOME attributes that are not stored in the database. For example, I want to save the "age" field in the model, but I only store the birthday information in the database (I can calculate the "age" after loading the DOB information). I tried to add a simple attribute to the model extension, but as far as I can tell, it ignored CakePHP. What is the right way to do this?

I am new to CakePHP, so forgive me if I miss something obvious.

+4
source share
5 answers

I would do this using the afterFind method in the model.

+9
source

It's been a while since I dealt with Cake, but why not just implement the getAge () method?

+3
source

If you use CakePHP 1.3, you can use the "virtual field": http://book.cakephp.org/view/1608/Virtual-fields [Cookbook 3.7.10]

[edit] It also works in CakePHP 2.x: http://book.cakephp.org/2.0/en/models/virtual-fields.html

The main advantage of this approach is that a virtual field is added to the model. Thus, the principles of MVC are respected.

example (MySQL):

var $virtualFields = array( 'age' => "YEAR(NOW()) - YourModelHere.dob" ); 
+2
source
0
source

Use the Cache class:

 $parametrs = array('age'=>21, 'name'=>'aziz'); Cache::write('myOptions', $parameters); Cache::read('myOptions'); 
-one
source

All Articles