dataProvider
类,封装了排序(sort)和分页(pagination)功能;
1、正常使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| use yii\data\ActiveDataProvider; $query = Post::find()->where(['status' => 1]); $provider = new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'pageSize' => 10, ], 'sort' => [ 'defaultOrder' => [ 'created_at' => SORT_DESC, 'title' => SORT_ASC, ] ], ]); $posts = $provider->getModels(); $totalCount = $provider->totalCount
|
2、联表查询,并联表排序
post model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public function getAuthor() { reutrn $this->hasOne(Article::className(),['id' => 'author_id]) } $query = Post::find() ->joinWith('author',true,'RIGHT JOIN') ->where(['status' => 1]); $provider = new ActiveDataProvider([ 'query' => $query, // 或 $query->asArray() 'pagination' => [ 'pageSize' => 10, ], 'sort' => [ 'defaultOrder' => [ 'created_at' => SORT_DESC, 'title' => SORT_ASC, ], 'attributes' => [ 'article_type' => [ 'asc' => ['article.type' => SORT_ASC], 'desc' => ['article.type' => SORT_DESC] ] ], ], ]);
|
- 当author表和post表都有type时,指明表名,如
article.type
- 事实上,当使用
ActiveDataProvider
时,post
表中的每个字段都是可以用来排序的
3、禁用分页:$provider->setPagination(false);
4、禁用排序:$provider->setSort(false);
1、单一排序:
1 2 3 4 5 6 7 8
| $sort = new Sort([ 'defaultOrder' => ['id' => SORT_DESC,], 'attributes' => [ 'id' ] ]); $data = TradeRecord::find()->orderBy($sort->orders)->asArray()->all();
|
2、混合排序:
主要根据bill_id排序;如果bill_id相同,再根据id排序;
1 2 3 4 5 6 7 8 9 10 11 12 13
| $sort = new Sort([ 'defaultOrder' => ['id' => SORT_DESC,], 'attributes' => [ 'id' => [ 'asc' => ['bill_id' => SORT_ASC,'id' =>SORT_ASC], 'desc' => ['bill_id' => SORT_DESC,'id' => SORT_DESC], 'default' => SORT_DESC, 'label' => 'id' ], ] ]); $data = TradeRecord::find()->orderBy($sort->orders)->asArray()->all();
|