yii1带有自定义SQL的CGridview

时间:2017-05-31 02:32:21

标签: mysql yii cgridview

我需要使用yii1 CGridView和自定义SQL。 我跟着this article

我已创建的模型内部

public function searchUserStats()
{
    $count = Yii::app()->db->createCommand()
                ->select('count(DISTINCT user_id)')
                ->from('casino_sg_sessions')
                ->queryScalar();

    $sql = '
            SELECT
                    SUM(bet) bet_sum,
                    SUM(win) win_sum,
                    SUM(bet_count) bet_count,
                    user_id,
                    userName,
                    modified
            FROM        
                (SELECT
                        (SELECT IFNULL(SUM(tr1.amount), 0) FROM casino_sg_transactions tr1 WHERE t.id = tr1.session_id AND tr1.action = \'bet\' ) AS bet, 
                        (SELECT IFNULL(SUM(tr2.amount), 0) FROM casino_sg_transactions tr2 WHERE t.id = tr2.session_id AND tr2.action = \'win\' ) AS win,
                        (SELECT count(0) FROM casino_sg_transactions tr3 WHERE t.id = tr3.session_id) AS bet_count,
                        t.user_id,
                        u.userName,
                        t.modified
                    FROM `casino_sg_sessions` t
                    INNER JOIN user u ON u.id = t.user_id
                    ORDER BY modified DESC
                ) user_stats
            GROUP BY user_id
            ORDER BY modified DESC
    ';
    $command = Yii::app()->db->createCommand($sql);

    $dataProvider = new CSqlDataProvider($command, array(
        'totalItemCount'=>$count,

        'pagination'=>array(
            'pageSize'=>15,
        ),
    ));


    return $dataProvider;

}

在控制器中:

$model = new CasinoSgSessions('searchUserStats');
$this->render('index', array(
        'model' => $model,
));

在视图中我称之为:

$this->widget('application.widgets.grid.CGridView', array(
    'dataProvider' => $model->searchUserStats(),
    'filter' => $model,
    'columns' => array(
        [
            'header' => 'User ID',
            'name'   => 'user_id',
            'value' => '$data->user_id',
            'htmlOptions' => array('width'=>'150px'),
        ],

    .....
    .....

我收到没有数据的分页网格。

花了很多时间现在放弃了,我做错了什么?

sql查询本身效果很好。

PS:我无法使用mysql视图并为视图创建模型。

PPS:查询会有点复杂,所以我看到的唯一方法就是通过SQL查询使用CGridView。

1 个答案:

答案 0 :(得分:0)

在模板中而不是

$data->user_id

我必须使用

$data['user_id']

绝对不是预期的行为。在我看来,他们没有听说过SOLID