I actually started writing this to ask for help, but found my error before I finished. Instead of letting it all go to waste I thought I would share my example. Hopefully it will help someone else.
I have the following relationship in my User model:
'email' => array(self::HAS_MANY, 'Email', 'user_id'),
Now I know that CGridView and HAS_MANY relationships don’t get along, but I’m stubborn and I had a special case. Each user has only one primary email so I wanted to identify this HAS_ONE relationship in the many emails of the user and not only use the primary email in CGridView, but also allow it to be contextually searched and filtered (ASC, DESC). This is how I did it:
User Model
class User extends CActiveRecord
{
public $email_primary;
public function rules()
{
return array(
array('email_primary', 'safe', 'on'=>'search'),
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->with = array(
'email'=>array(
'together'=>true
)
);
$criteria->compare('username',$this->username,true);
$criteria->compare('create_time',$this->create_time);
$criteria->compare('profile.lastname',$this->profile_lastname,true);
$criteria->compare('profile.firstname',$this->profile_firstname,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'attributes'=>array(
'email_primary'=>array(
'asc'=>'email.email',
'desc'=>'email.email DESC',
),
'*',
),
),
));
}
public function primaryEmail() {
foreach ($this->email as $email) {
if($email->primary == 1)
{
return $this->email_primary = $email->email;
}
}
}
Grid View
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'user-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array(
'name'=>'email_primary',
'header'=>'Email',
'value'=>'$data->primaryEmail()',
),
array(
'class'=>'CButtonColumn',
),
),
)); ?>
All questions and criticisms welcome!