在Yii 1.1中,此代码适用于默认排序:
$dataProvider = new CActiveDataProvider('article',array(
'sort'=>array(
'defaultOrder'=>'id DESC',
),
));
如何在Yii2中设置默认排序?
尝试了以下代码,但没有结果:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['defaultOrder'=>'topic_order asc']
]);
我认为有合适的解决方案。配置yiidataSort
对象:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['topic_order' => SORT_ASC]],
]);
官方文档链接
或
$dataProvider->setSort([
'defaultOrder' => ['topic_order'=>SORT_DESC],
'attributes' => [...
defaultOrder包含一个数组,其中键是列名,值是SORT_DESC
或SORT_ASC
,这就是下面代码不起作用的原因。
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['defaultOrder'=>'topic_order asc']
]);
正确的方式
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'topic_order' => SORT_ASC,
]
],
]);
注意:如果查询已经指定了orderBy子句,则最终用户(通过排序配置)给出的新排序指令将附加到现有的orderBy子句中。任何现有的限制和偏移子句都将被来自最终用户的分页请求覆盖(通过分页配置)。
您可以详细了解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();
如果您有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];
尝试这个
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$sort = $dataProvider->getSort();
$sort->defaultOrder = ['id' => SORT_ASC];
$dataProvider->setSort($sort);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['iUserId'=>SORT_ASC]]
]);
您可以使用类似的排序属性
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['topic_order' => SORT_ASC]],]);
如果你想为examle topic_order1和topic_older2按两个feild排序,你可以这样做
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['topic_order1' => SORT_ASC,
'topic_order2' =>SORT_DESC]]]);
如指南中所述,您必须通过配置其排序属性来指定数据提供程序的排序行为,该属性与yii\data\sort 的配置相对应
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['topic_order' => SORT_ASC]],
]);
$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]]
]);
您可以修改类似的搜索模型
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => ['user_id ASC, document_id ASC']
]
]);