Yii2 添加相关属性进行排序

问题描述 投票:0回答:1

我有普通的 ModelSearch 和 ActiveDataProvider,我想添加一个虚拟/相关属性来在 gridview 中排序。如果我使用 setSort 进行操作,并且仅添加此属性,则所有其他属性都不再可排序。是否有内置方法可以“添加”属性进行排序?非常感谢! public function search($params) { $query = Za::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'sort' => ['defaultOrder' => ['aonr' => SORT_ASC]], 'pagination' => [ 'pageSize' => 15, ], ]); $dataProvider->setSort([ 'attributes' => [ 'lwnr' => [ 'asc' => ['lwnr' => SORT_ASC], 'desc' => ['lwnr' => SORT_DESC], 'label' => 'lwnr', 'default' => SORT_DESC, ], ] ]); $this->load($params); ... }

	
php sorting gridview yii2 virtual-attribute
1个回答
6
投票
all

要排序的列,而不仅仅是关系中的列。 如果您想添加一列,您可以尝试此操作(将当前现有的排序属性与新的排序属性合并):

$dataProvider->setSort([ 'attributes' => array_merge( $dataProvider->getSort()->attributes, [ 'lwnr' => [ 'asc' => ['lwnr' => SORT_ASC], 'desc' => ['lwnr' => SORT_DESC], 'label' => 'lwnr', 'default' => SORT_DESC, ], ] ), ]);

或者您可以手动添加缺少的属性/列(这是一个更好的主意)

$dataProvider->setSort([ 'attributes' => [ 'lwnr' => [ 'asc' => ['lwnr' => SORT_ASC], 'desc' => ['lwnr' => SORT_DESC], 'label' => 'lwnr', 'default' => SORT_DESC, ], // Other attribute 'id' => [ 'asc' => ['id' => SORT_ASC], 'desc' => ['id' => SORT_DESC], ], ... ], ]);

另一种方式:

$dataProvider->getSort()->attributes['lwnr'] = [ 'asc' => ['lwnr' => SORT_ASC], 'desc' => ['lwnr' => SORT_DESC], 'label' => 'lwnr', 'default' => SORT_DESC, ];

	
© www.soinside.com 2019 - 2024. All rights reserved.