通常應用和需求的複雜程度,咱們使用ActiveDataProvider均可以搞定,除非咱們實在沒法經過QueryBuilder來構造一個複雜的SQL的時候,SqlDataProvider就是你的好夥伴了。php
和名字同樣,SqlDataProvider接收一個原生的SQL語句而且能生成一個帶有參數的dataProvider,而且前臺的GridView等均可以很好的使用它。sql
直接上代碼數組
$totalCount = Yii::$app->db->createCommand('SELECT COUNT(*) FROM user WHERE sex=:sex', ['sex:' => 1]) ->queryScalar(); $dataProvider = new SqlDataProvider([ 'sql' => 'SELECT * FROM userWHERE sex=:sex', 'params' => [':sex' => 1], 'totalCount' => $totalCount, //'sort' =>false,//若是爲假則刪除排序 'sort' => [ 'attributes' => [ 'username' => [ 'asc' => ['username' => SORT_ASC], 'desc' => ['username' => SORT_DESC], 'default' => SORT_DESC, 'label' => '用戶名', ], 'sex' => [ 'asc' => ['sex' => SORT_ASC], 'desc' => ['sex' => SORT_DESC], 'default' => SORT_DESC, 'label' => '性別', ], 'created_on' ], ], 'pagination' => [ 'pageSize' => 10, ], ]); return $dataProvider;
<?= GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], [ 'label' =>"暱稱", 'attribute' => 'nickname', 'value'=>function($data){ return $data["nickname"]; } ], 'username', 'sex', 'created_on', ['class' => 'yii\grid\ActionColumn'], ], ]); ?>
你看懂了沒,和ActiveDataProvider一個重要區別就是它數組的形式,而ActiveDataProvider是對象形式。微信
好,此篇結束,送給那些喜歡寫原生SQL或不得不寫原生SQL的小夥伴。app
本文原創發佈於微信公衆號 北哥小報 , 嚴謹的原創技術文,Q羣:171277552。yii