Is there an easy way to add custom fields to the model? Let's say I have a user table with three fields: id, name and surname. I want this:
$user = User::model()->findByPk(1); $echo $user->fullName;
Please note: I want this custom field to be added via sql, smth like
$c = new CDbCriteria(); $c->select = 'CONCAT("user".name, "user".surname) as fullName'; $user = User::model()->find($c);
The problem is that the fullName property is not set.
UPD
here is the code for a slightly more complicated problem - a custom field from another table. Here's how to do it:
$model = Application::model(); $model->getMetaData()->columns = array_merge($model->getMetaData()->columns, array('fullName' => 'CONCAT("u".name, "u".surname)')); $c = new CDbCriteria(); $c->select = 'CONCAT("u".name, "u".surname) as fullName'; $c->join = ' left join "user" "u" on "t".responsible_manager_id = "u".id'; $model->getDbCriteria()->mergeWith($c); foreach ($model->findAll() as $o) { echo '<pre>'; print_r($o->fullName); echo '</pre>'; }
source share