如何在Yii2中实现以下排序:
SELECT * FROM `orders` order by case when status != 'ORDER_DONE' then 1 else 2 end,status
我想将ORDER_DONE的状态删除到底部。有什么想法吗?
答案 0 :(得分:0)
自2.0.7起,您可以将yii\db\Expression
传递给orderBy()
,所以请执行以下操作:
(new \yii\db\Query)
->from('orders')
->orderBy(new \yii\db\Expression('CASE WHEN status != "ORDER_DONE" THEN 1 ELSE 2 END, status'))
->all();
用于分类数据提供者使用:
'sort' => [
'attributes' => [
'onlinedate' => [
'asc' => [new \yii\db\Expression('CASE WHEN status != "ORDER_DONE" THEN 1 ELSE 2 END, status')],
'desc' => [new \yii\db\Expression('CASE WHEN status = "ORDER_DONE" THEN 1 ELSE 2 END, status')],
],
],
]