Yii2并在ArrayDataProvider中排序

时间:2016-05-07 06:15:19

标签: php yii yii2

我正在使用ArrayDataProvider,我想知道如何在视图中进行排序链接 $sort->link('date')yii/data/Sort

1 个答案:

答案 0 :(得分:8)

关注this (yii\data\sort)this (yii\data\ArrayDataProvider)文档

你能做的就是这样:

$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',
        ],
        // or any other attribute
    ],
]);

之后,您可以将其放入数组数据提供程序

$query = new Query;
$provider = new ArrayDataProvider([
    'allModels' => $query->from('post')->all(),
    'sort' => $sort, // HERE is your $sort
    'pagination' => [
        'pageSize' => 10,
    ],
]);
// get the posts in the current page
$posts = $provider->getModels();

最后在你看来:

// any attribute you defined in your sort defination
echo $sort->link('name') . ' | ' . $sort->link('age');