4

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>';
    }
1
  • Pretty hacky solution though... I don't think that manually changing meta data is good style. Commented Sep 10, 2012 at 9:16

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

With Yii's __get methods, you can call that function just like it was a regular column too: $user->fullName
When you write something like $user->fullName, fullName can be part of $user for a few different reasons. It could be a member variable of the User active record, it could be a column in the User table, it could be the name of a relation that User has, it could be a member function named getFullName(). I think that is all and in the order they are checked.
Translating $user->fullName to $user->getFullName() is part of CComponent, the base class for all Yii classes. For ActiveRecord, additional attribute/relation checks are done FIRST: code.google.com/p/yii/source/browse/tags/1.1.9/framework/db/ar/…
0

In model

public function getMetaData(){
        $data = parent::getMetaData();
        $data->columns['fullName'] = array('name' => 'fullName');
        return $data;
    }

Thus not recommended

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.