我正在尝试使用 Yii 2
实现分页系统并使用 SQL 数据提供程序,但出现以下错误:
Invalid argument supplied for foreach()
这是由sort
类中的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_1
sort_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,
],
...
],