Yii2:当排序升序时,如何将空值放到对象列表的末尾?

时间:2015-03-16 07:28:57

标签: php activerecord yii2

这是我的DataProvider:

$dataProvider = new ActiveDataProvider([
    'query'      => $query,
    'pagination' => ['pageSize' => 50],
    'sort'       => [
        'defaultOrder' => [
            'priority'      => SORT_DESC,
            'date_targeted' => SORT_ASC
        ]
     ]
]);

enter image description here

enter image description here enter image description here 我想要的是移动("未设置")到结果的末尾。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以在select中添加新字段。并在IF案例中设置:

$query->select([
    '*', 
    new \yii\db\Expression('IF(date_targeted IS NULL, 1, 0) AS date_targeted_flag')
]);

sort添加date_targeted_flag

'sort' => [
    'defaultOrder' => [
        'date_targeted_flag' => SORT_ASC,
        'priority'           => SORT_DESC,
        'date_targeted'      => SORT_ASC
    ],
    'attributes' => [
        'date_targeted_flag',
        'priority',
        'date_targeted'
    ]
]

这很好用 - herehere