2015-06-08 70 views
0

我試圖表明使用的GridView從視圖數據庫中的數據,但我有問題Yii2:不能顯示的數據中的Widget的GridView

錯誤信息

未知方法 - 警予\基地\ UnknownMethodException 調用未知的方法:警予\ 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'], 
     ], 
    ]); ?> 

我怎樣才能解決這個問題?

回答

0

的GridView查找數據提供程序,而不是陣列的ActiveRecord模型已發出:

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

在控制器/的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, 
]); 
+0

我該如何實現這個到我的sql? – ariyandi

0

你可以試試這個:
在Controller.php這樣文件:

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

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

你的觀點文件似乎是真的。只需在控制器文件中添加上面的代碼。