Yii2原生SQL+GridView分页问题 [ 未指定版本 ]
在sql比较复杂,用orm不好实现的情况下需要写原生sql还要用GirdView展现数据;
我的思路是这样的(已实现):
//Controller
$sql = 'select a.id,b.name,c.age from a,b,c where xxx';
$q = Yii::$app->db2->createCommand($sql)->queryAll();
$pages = new Pagination([
'totalCount'=>count($q),
]);
$list = Yii::$app->db2->createCommand($sql." limit ".$pages->limit." offset ".$pages->offset."")->queryAll();
$dataprovider = new ArrayDataProvider([
'allModels' => $list,
]);
return $this->render('circle',[
'dataprovider'=>$dataprovider,
'pages'=>$pages,
]);
//View
<?= GridView::widget([
'dataProvider'=>$dataprovider,
//不显示gridview的分页,在这指定totalCount属性不好使(问题就在这)
'pager'=>[
'options'=>['class'=>'hidden']
],
'columns'=>[
//此处略去n多字
],
]) ?>
//单独展示分页
<?= LinkPager::widget([
'pagination'=>$pages,
]) ?>
虽然这样能实现我想要的结果,但是总感觉姿势不对.求大神指点
大裤衩子 补充于 2014-09-18 09:43
格式真难弄啊啊啊...
最佳答案
-
$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, ], ]); // get the user records in the current page $models = $dataProvider->getModels();
共 1 条回复fdzaxd 觉得很赞
其他 6 个回答
-
那么,我也给个优雅的回答
controller:public function actionArticlelist(){ $query = Article::find()->with('cate'); $provider = new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'pageSize' => 3, ], 'sort' => [ 'defaultOrder' => [ //'created_at' => SORT_DESC, 'title' => SORT_ASC, ] ], ]); return $this->render('artlist', [ 'model' => $query, 'dataProvider' => $provider, ]); }
视图
use yii\grid\GridView; GridView::widget([ 'dataProvider' => $dataProvider, 'summary'=>false,//关闭顶部总条数 'pager'=>[ //'options'=>['class'=>'hidden']//关闭自带分页 'firstPageLabel'=>"First", 'prevPageLabel'=>'Prev', 'nextPageLabel'=>'Next', 'lastPageLabel'=>'Last', ], //'layout'=>false, 'columns' => [//other coding
共 2 条回复
大裤衩子 北京
注册时间:2013-02-17
最后登录:2023-12-29
在线时长:91小时52分
最后登录:2023-12-29
在线时长:91小时52分
- 粉丝92
- 金钱8528
- 威望120
- 积分10638