2

我在CGrid使用``页面中的关系模型对关系数据进行排序时遇到问题。

简单来说我的场景:

我有一个用户 model: Entities=> id,username个人资料 Model: Entities=> id, firstname,lastname, user_id,等。

我想列出profile model 和usernamefrom user modelin CGrid,以便排序和搜索很好。在我的情况下,排序 username是由user_idnot by完成的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_idnot by的基础上完成的username。我缺少这样做的任何东西。请建议。

参考:在这里(我也尝试通过声明一个公共变量作为链接中的建议,但机器人正在工作。)

编辑:问题修复后。也感谢这个链接。

4

1 回答 1

3

嗯,你找到的 wiki 页面确实是一个好的开始......

这是执行此操作的另一种方法:

在您的个人资料模型中:

// 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',
        // .....
    ),
);
于 2013-04-19T13:16:36.590 回答