在使用“页面”中的关系模型对关系数据进行排序时,我在CGrid
中遇到了问题。
我有用户 model: Entities=> id,username
还有个人资料 Model: Entities=> id, firstname,lastname, user_id,
等。
我想在profile mode
的{{1}}中列出username
l和user model
,以便排序和搜索烫发。在我的情况下,排序CGrid
由username
而不是user_id
完成。我想通过username
进行搜索,所以我会执行以下操作,
username
$model = new Profile('search');
$model -> unsetAttributes();// clear any default values
if (isset($_GET['Profile']))
$model -> attributes = $_GET['Profile'];
$this -> render('MyPage', array('model' => $model ));
public function relations() {
// NOTE: you may need to adjust the relation name and the related
// class name the relations automatically generated below.
return array(
'user' => array(self::BELONGS_TO, 'user', 'user_id'),);
}
array( 'xxx,yyy,user_name', 'safe', 'on'=>'search' ),
if(!empty($this->user_id)){
$criteria->with='user';
$criteria->order = ::app()->request->getParam('sort');// 'username ASC'
}
$criteria -> compare('user.username', $this->user_id, true);
在排序过程中,排序工作完美,但排序是基于$this->widget('zii.widgets.grid.CGrid', array(
'id'=>'profile-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
array('name'=>'user_id',
'header'=>User::model()->getAttributeLabel('username'),
'value' =>'$data->getRelated(\'user\')->username',
'type'=>'raw',
'htmlOptions'=>array('style'=>'text-align: center'),),
---------------
而不是user_id
进行的。我缺少的任何东西都是这样做的。请建议。
参考:Here(我也试过通过声明一个公共变量作为链接中的建议但是bot工作。)
编辑:问题发布后。 还要感谢this链接。
答案 0 :(得分:3)
好吧,你找到的维基页面确实是一个好的开始......
以下是另一种方法:
在您的个人资料模型中:
// private username attribute, will be used on search
private $_username;
public function rules()
{
return array(
// .....
array('username', 'safe', 'on'=>'search'),
// .....
);
}
public function getUsername()
{
// return private attribute on search
if ($this->scenario=='search')
return $this->_username;
// else return username
if (isset($this->user_id)) && is_object($this->user))
return $this->user->username;
}
public function setUsername($value)
{
// set private attribute for search
$this->_username = $value;
}
public function search()
{
// .....
$criteria->with = 'user';
$criteria->compare('user.username', $this->username, true);
// .....
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'attributes'=>array(
'username'=>array('asc'=>'user.username', 'desc'=>'user.username DESC'),
'*',
),
),
));
}
在您看来,您应该尝试:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'profile-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
// .....
'username',
// .....
),
);