Yii2 添加相关属性排序

Yii2 add related attribute to sort

我有正常的 ModelSearch 和 ActiveDataProvider,我想在 gridview 中添加一个 virtual/related 属性来排序。如果我使用 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);
...
}

您可以使用 setSort 方法设置可排序属性,但在这种情况下,您需要设置 所有 您想要排序的列,而不仅仅是关系中的列。

如果你想添加一列,你可以试试这个(将当前现有的排序属性与新的排序属性合并):

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

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

    $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,
                ];