- In the model create property for related attribute:
class Post extends CActiveRecord
{
public $category_name;
// other stuff
}
- Add the property name to the rules() method of model (in the safe/search section):
public function rules()
{
return array(
// other stuff
array('id, category_id, title, body, created_date, category_name', 'safe', 'on'=>'search'),
);
}
- In the search() method of the model add the related model and related property:
public function search()
{
$criteria=new CDbCriteria;
$criteria->with = array('category'); // related model
$criteria->compare('id',$this->id,true);
$criteria->compare('category_id',$this->category_id,true);
$criteria->compare('title',$this->title,true);
$criteria->compare('body',$this->body,true);
$criteria->compare('created_date',$this->create_date,true);
$criteria->compare('category.name',$this->category_name,true); // related property
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder' => 't.id desc',
'attributes' => array(
'category_name' => array(
'asc'=>'category.name',
'desc'=>'category.name DESC',
),
'*',
),
)
));
}
- In the view file (views/post/admin.php) add related property in column array of CGridView widgets:
$this->widget('zii.widgets.grid.CGridView', array(
// other stuff
'columns'=>array(
'id',
'category_id',
'title',
'created_date',
array(
'name' => 'category_name',
'header' => 'Category Name',
'value' => '$data->category->name',
),
),
// other stuff
));