Laravel按条件eloquent或sql排序

时间:2015-03-17 14:08:16

标签: sql laravel-4 eloquent query-builder

我在数据库表中有这些timestamp列 - expiration,edit,created_at。我需要通过'编辑'订购,如果项目到期'日期大于今天的日期,否则我需要按照'created_at'订购。

我正在尝试这样的事情,但它没有正常工作

$items = $items
->orderBy(DB::raw("CASE WHEN expiration >= $time THEN edit ELSE created_at END"), 'DESC')
->get();

$items = $items
->orderBy(DB::raw("CASE WHEN expiration >= $time THEN edit END"), 'DESC')
->orderBy('created_at', 'DESC')
->get();

变量$ time是正确的,所以我的问题在于查询。 样本数据:

id   name   created_at             expiration             edit
1.   it1    2015-03-16 15:42:40    0000-00-00 00:00:00    2015-03-16 15:42:40
2.   it2    2015-03-16 15:37:27    2015-03-16 00:00:00    2015-03-16 15:37:27
3.   it3    2015-03-16 12:36:50    2015-03-27 00:00:00    2015-03-16 14:52:19

我需要按顺序 - > it3,it1,it2

可变$ time = 2015-03-17

3 个答案:

答案 0 :(得分:5)

如果你想使用' Case'按顺序,有两种方式: 假设用户想要查看" Order By"搜索文字 即" tamil nadu"

1:

->orderByRaw('case 
    when `title` LIKE "%tamil nadu%" then 1
    when `title` LIKE "%tamil%"  then 2 
    when `title` LIKE "%nadu%"  then 3 
    else 4 end');

2: 将您的条件/案例通过条款

$searchText = explode(" ", $searchingFor);
$orderByRowCase = 'case when title LIKE "%tamil nadu%" then 1 ';
foreach ($searchText as $key => $regionSplitedText) {
   $Key += 2;
   $orderByRowCase .= ' when title LIKE "%' . $regionSplitedText . '%" then ' . $Key . '';
}
$orderByRowCase .= ' else 4 end';   

(您的Laravel查询)

->orderByRaw($orderByRowCase);

答案 1 :(得分:0)

->orderByRaw(
     "CASE WHEN expiration >= {$time} THEN edit ELSE created_at END DESC"
)

编辑:您的示例显示您想要其他内容。您的设置顺序为it1, it2, it3。要理解这种行为,请尝试以下方法:

select 
  name, 
  case when expiration >= '2015-03-17' then edit else created_at end as order_value 
from YOUR_TABLE 
order by case when expiration >= '2015-03-17' then edit else created_at end desc;

它将显示order by子句的值:

| name | order_value         |
| it1  | 2015-03-16 15:42:40 |
| it2  | 2015-03-16 15:37:27 |
| it3  | 2015-03-16 14:52:19 |

所以,我认为你实际上需要按IS_EXPIRED订购,然后按日期订购?然后你需要两个case条款,或类似的东西:

->orderByRaw(
     "CASE WHEN expiration >= {$time} THEN concat('1 ', edit)
           ELSE concat('0 ',created_at) END DESC"
)

答案 2 :(得分:0)

->orderByRaw("CASE WHEN expiration >=".$time." THEN edit END DESC")->get();