phpyiicustom-attributes

Yii: adding custom fields


Is there a simple way of adding custom fields to a model? Say I have a table "user" with 3 fields: id, name and surname. I want this:

$user = User::model()->findByPk(1);
$echo $user->fullName; // echoes name and surname

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);

Problem is that fullName property is not set.

UPD:

here is the code for a little bit trickier problem -- custom field from another table. This is how it's done:

    $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>';
    }

Solution

  • You can add a function to the User class:

    public function getFullName() { return $this->name.' '.$this->surname; }
    

    This will return the full name as if it were an attribute from the database. This is much easier than adding a calculated column to the SQL.