Welcome to the Cookbook

loading...

3.7.10.1 Creating virtual fields

Creating virtual fields is easy. In each model you can define a $virtualFields property that contains an array of field => expressions. An example of a virtual field definition using MySQL would be:

var $virtualFields = array(
    'full_name' => 'CONCAT(User.first_name, " ", User.last_name)'
);
  1. var $virtualFields = array(
  2. 'full_name' => 'CONCAT(User.first_name, " ", User.last_name)'
  3. );
And with PostgreSQL:
var $virtualFields = array(
    'name' => 'User.first_name || \' \' || User.last_name'
);
  1. var $virtualFields = array(
  2. 'name' => 'User.first_name || \' \' || User.last_name'
  3. );

In subsequent find operations, your User results would contain a name key with the result of the concatenation. It is not advisable to create virtual fields with the same names as columns on the database, this can cause SQL errors.

It is not always useful to have User.first_name fully qualified. If you do not follow the convention (i.e. you have multiple relations to other tables) this would result in an error. In this case it may be better to just use first_name || \'\' || last_name without the Model Name.