Yii2:无法在Widget GridView中显示数据

时间:2015-06-08 02:01:39

标签: mysql gridview frameworks yii2

我尝试使用gridview在视图中显示来自数据库的数据,但是我遇到了问题

错误消息

  

未知方法 - yii \ base \ UnknownMethodException   调用未知方法:yii \ db \ ActiveQuery :: getCount()

我的控制器

public function actionIndex()
{
    $sql = "SELECT presensi.presensi_tanggal 'tanggal', sum(if( hadir.keteranganhadir_id='1',1,0)) 'hadir', sum(if( hadir.keteranganhadir_id='2',1,0)) 'tidak_hadir', count(*) 'total' FROM hadir, keteranganhadir, presensi where hadir.keteranganhadir_id = keteranganhadir.keteranganhadir_id and hadir.presensi_id = presensi.presensi_id group by presensi.presensi_tanggal";

    $model = Hadir::findBySql($sql)->all();

    return $this->render('index', [
        'hadir' => $model,
    ]);
}

我的观点

<?= GridView::widget([
        'dataProvider' => $hadir,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'tanggal',
            'hadir',
            'tidak_hadir',
            'total',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

Gridview查找dataprovider,而不是您发送的activerecord模型数组:

http://www.yiiframework.com/doc-2.0/yii-data-sqldataprovider.html

在你的controller / actionIndex

$count = Yii::$app->db->createCommand('
    SELECT COUNT(*) FROM user WHERE status=:status
', [':status' => 1])->queryScalar();

$dataProvider = new SqlDataProvider([
    'sql' => 'SELECT * FROM user WHERE status=:status',
    'params' => [':status' => 1],
    'totalCount' => $count,
    'sort' => [
        'attributes' => [
            'age',
            'name' => [
                'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
                'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Name',
            ],
        ],
    ],
    'pagination' => [
        'pageSize' => 20,
    ],
]);
return $this->render('index', [
    'hadir' => $dataProvider,
]);

答案 1 :(得分:0)

你可以试试这个:
在Controller.php文件中:

public function actionIndex()
    {
        $searchModel = new InvoiceSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

您的查看文件似乎属实。只需在控制器文件中添加上述代码即可。