Yii: adding custom fields

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

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>'; } 
+4
source share
2 answers

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 simpler than adding a computed column to SQL.

+9
source

In the model

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

Therefore not recommended

0
source

Source: https://habr.com/ru/post/1394678/


All Articles