yii2使用订单案例对ActiveDataProvider中的默认顺序进行多重排序

时间:2017-01-04 08:07:43

标签: sorting yii2 case case-when

我正在使用Yii2创建一个网站,我想用这样的多个字段排序:

SELECT * FROM tbl_product t
ORDER BY
CASE
    WHEN t.product_sale_price IS NULL THEN t.product_price
    ELSE t.product_sale_price
END

以上查询,这组数据:

Product | product_price | product_sale_price
--------|---------------|-------------------
Prod A  | 2000          | 1200
Prod B  | 1500          | NULL
Prod C  | 1800          | NULL
Prod D  | 1000          | 500

将成为:

Product | product_price | product_sale_price
--------|---------------|-------------------
Prod D  | 1000          | 500
Prod A  | 2000          | 1200
Prod B  | 1500          | NULL
Prod C  | 1800          | NULL

我们如何将它放在ActiveDataProvider的defaultOrder中?我试过了:

return new ActiveDataProvider([
    'sort' => [
        'defaultOrder' => ['product_sale_price' => SORT_ASC, 'product_price' => SORT_ASC],
        'enableMultiSort' => true,
    ],
]);

return new ActiveDataProvider([
    'sort' => [
        'defaultOrder' => '(CASE WHEN product_sale_price IS NULL THEN product_price ELSE product_sale_price END ASC)',
    ],
]);

两者都不起作用。我是怎么做的?

1 个答案:

答案 0 :(得分:1)

例如:https://gist.github.com/XAKEPEHOK/9dfd72d1beb55ddacdcbac6bb61599df

然后

$expression= new Expression('(CASE WHEN product_sale_price IS NULL THEN product_price ELSE product_sale_price END ASC)');

return new ActiveDataProvider([
    'sort' => [
        'class'=><here define your sort extend class>
        'defaultOrder' => $expression,
    ],
]);

或者:

$dataProvider = new ActiveDataProvider([
            'query' => $query,            
            'sort'  => [
                'attributes' => [
                    '<attribute that you want sort>' => [
                        'asc' => [new Expression('(CASE WHEN product_sale_price IS NULL THEN product_price ELSE product_sale_price END ASC)')],
                        'desc' => [new Expression('(CASE WHEN product_sale_price IS NULL THEN product_price ELSE product_sale_price END ASC)')],
                   ],
                    // more attribute definitions here
                ],
                'defaultOrder' => ['<attribute that you want sort>' => SORT_DESC],
        ]);