尝试使用 sql 数据提供程序在 Yii 2 中创建分页系统时遇到问题

Having issue trying to create pagination system in Yii 2 with sql data provider

我正在尝试使用 Yii 2 实现分页系统并使用 SQL Data Provider 但我收到以下错误:

Invalid argument supplied for foreach()

这是由 sort class 中的 getOrders Yii 方法中的 line 215 引起的;这是由下面代码中的这个位引起的 $models = $dataProvider->getModels();.

通用代码如下:

$sql = $this->db->createCommand("SELECT COUNT(*) FROM some_table WHERE some_id=:some_id");
$sql->bindValue(':some_id', $this->some_id);
$count = $sql->queryScalar();

$dataProvider = new SqlDataProvider([
    'sql' => 'SELECT * FROM some_table WHERE some_id=:some_id',
    'params' => [':some_id' => $this->some_id],
    'totalCount' => $count,
    'sort' => [
        'attributes' => [
            'sort_way_1' => [
                'asc' => ['col_1' => SORT_DESC, 'col_2' => SORT_ASC, 'col_3' => SORT_ASC],
                'desc' => ['col_1' => SORT_DESC, 'col_2' => SORT_DESC, 'col_3' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Sort Way 1',
            ],
            'sort_way_2' => [
                'asc' => ['col_1' => SORT_DESC, 'col_4' => SORT_ASC, 'col_3' => SORT_ASC],
                'desc' => ['col_1' => SORT_DESC, 'col_4' => SORT_DESC, 'col_3' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Sort Way 2',
            ],
            'sort_way_3' => [
                'asc' => ['col_1' => SORT_DESC, 'col_5' => SORT_ASC, 'col_3' => SORT_ASC],
                'desc' => ['col_1' => SORT_DESC, 'col_5' => SORT_DESC, 'col_3' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Sort Way 3',
            ],
            'sort_way_4' => [
                'asc' => ['col_1' => SORT_DESC, 'col_6' => SORT_ASC, 'col_3' => SORT_ASC],
                'desc' => ['col_1' => SORT_DESC, 'col_6' => SORT_DESC, 'col_3' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Sort Way 4',
            ],
        ],
        'enableMultiSort' => false,
        'defaultOrder' => [
                           'col_1' => SORT_DESC,
                           'col_2' => SORT_DESC,
                           'col_3' => SORT_DESC,
                           ],
    ],
    'pagination' => [
        'pageSize' => $this->per_page,
        'page' => $this->page,
        'pageSizeLimit' => [5,100],
        'pageSizeParam' => 'per_page',
        'totalCount' => $count,
    ],
]);

$models = $dataProvider->getModels();

谁能告诉我我做错了什么?

问题出在 defaultOrder 声明中。

您应该只使用排序属性部分中声明的属性(在您的情况下它们是 sort_way_1sort_way_4)。

sort_way_1 降序排列只需简单地使用:

'defaultOrder' => ['sort_way_1' => SORT_DESC],

并且无需复制所有列,因为您已在此处明确描述:

'sort_way_1' => [
    ...
    'desc' => [
        'col_1' => SORT_DESC,
        'col_2' => SORT_DESC,
        'col_3' => SORT_DESC,
    ],
    ...
],