Yii2数据提供者默认排序


99

在Yii 1.1中,此代码适用于默认排序:

$dataProvider = new CActiveDataProvider('article',array(
    'sort'=>array(
        'defaultOrder'=>'id DESC',
    ),
));

如何在Yii2中设置默认排序?

尝试以下代码,但没有结果:

$dataProvider = new ActiveDataProvider([
    'query' => $query,
    'sort' => ['defaultOrder'=>'topic_order asc']
]);

Answers:




15

defaultOrder包含一个数组,其中key是列名,value是a SORT_DESCSORT_ASC这就是下面的代码不起作用的原因。

$dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => ['defaultOrder'=>'topic_order asc']
    ]);

正确的方法

$dataProvider = new ActiveDataProvider([
    'query' => $query,
    'sort' => [
        'defaultOrder' => [
            'topic_order' => SORT_ASC,
        ]
    ],
]);

注意:如果查询已经指定了orderBy子句,则最终用户(通过sort配置)给出的新排序指令将附加到现有的orderBy子句中。来自终端用户的分页请求(通过分页配置)将覆盖任何现有的limit和offset子句。

您可以从Yii2数据提供者指南中详细了解

通过在查询中传递排序对象进行排序

 $sort = new 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',
            ],
        ],
    ]);

    $models = Article::find()
        ->where(['status' => 1])
        ->orderBy($sort->orders)
        ->all();

6

如果您有CRUD(索引),并且需要设置默认排序方式,以对GridView或ListView或其他进行排序...示例

public function actionIndex()
{
    $searchModel = new NewsSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    // set default sorting
    $dataProvider->sort->defaultOrder = ['id' => SORT_DESC];

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

您需要添加

$dataProvider->sort->defaultOrder = ['id' => SORT_DESC];

2

尝试这个

$dataProvider = new ActiveDataProvider([
    'query' => $query,
]);

$sort = $dataProvider->getSort();

$sort->defaultOrder = ['id' => SORT_ASC];

$dataProvider->setSort($sort);


-1

您可以像这样修改搜索模型

$dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => [
            'defaultOrder' => ['user_id ASC, document_id ASC']
        ]
    ]);

-2
    $modelProduct       =   new Product();
    $shop_id            =   (int)Yii::$app->user->identity->shop_id;

    $queryProduct       =   $modelProduct->find()
                            ->where(['product.shop_id'  => $shop_id]);


    $dataProviderProduct    =   new ActiveDataProvider([
                                    'query'         =>  $queryProduct,
                                     'pagination' => [ 'pageSize' => 10 ],
                                    'sort'=> ['defaultOrder' => ['id'=>SORT_DESC]]
                                ]); 
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.