【问题标题】:how to apply sorting on model method in CGridView Yii如何在 CGridView Yii 中对模型方法应用排序
【发布时间】:2014-10-01 15:26:07
【问题描述】:

我有用户模式l,其中包含一个计算每位用户平均收入的函数。现在我想在与 getAvgRevenue() 函数关联的列上应用 CGridView 中的排序。虽然许可证是用户模型中的关系。

这是我的代码,

 public class User{
     $user_id;
     $email;
     public function getAvgRevenue(){
        $count = 0;
        $revenue = 0;
        foreach ($this->license as $license){

            $revenue += $license->price;
            $count++;                
        }

        if($count!= 0){
            $averageRevenue = $revenue/$count;
            return $averageRevenue;
        }
        else{
            return null;
        }
      }

}

在控制器中

  $modelUser = new CActiveDataProvider('User', array( 
            'sort' => array(
                    'attributes' => array(
                            'user_id',
                            'email',
                            'averagerevenue'
                    ),
                    'defaultOrder' => array(
                            'user_id' => CSort::SORT_ASC,
                    ),
            ),
     ));

在视图中

  <?php $this->widget('zii.widgets.grid.CGridView', array(
     'id' => 'user-grid',
    'dataProvider' => $modelUser,
     'columns' => array(
            array(
                    'header' => 'User ID',
                    'name' => 'user_id',
            ),
            array(
                    'header' => 'Email',
                    'name' => 'email',
            ),
            array(
                'header'=>'Average Revenue',
                'value'=>'$data->averagerevenue',
            ),
        )
    ));

?>

排序适用于 user_idemail,但 平均收入列 不可排序。如何在 CActiveDataprovider 的 sort() 中指定模型方法 请帮我解决问题。

【问题讨论】:

    标签: php yii cgridview


    【解决方案1】:

    试试这个:

    $modelUser = new CActiveDataProvider('User', array( 
            'sort' => array(
                    'attributes' => array(
                            'user_id',
                            'email',
                            'avgRevenue' //here's the change for you
                    ),
                    'defaultOrder' => array(
                            'user_id' => CSort::SORT_ASC,
                    ),
            ),
     ));
    

    你的 gridview 列应该是:

    array(
                'header'=>'Average Revenue',
                'value'=>'avgRevenue',
            ),
    

    你可以在这里阅读更多信息:

    http://www.yiiframework.com/wiki/167/understanding-virtual-attributes-and-get-set-methods/

    【讨论】:

    • 感谢您的回复,我已经尝试过了,但它不起作用。没有拼写问题。
    猜你喜欢
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多