一、問題描述:
users數據表有兩個字段 創建時間 created_at ?真實姓名 real_name
現在展示users的list需要的排序方式為 有real_name的排后面,沒有的排前面;而且兩部分都按created_at desc 排序
id ? ? ? ? created_at ? ? ? ? ? real_name
1 ? ? ? ? ? ?2016-01 ? ? ? ? ? ? ? 40
2 ? ? ? ? ? ?2016-02 ? ? ? ? ? ? ? ?null
3 ? ? ? ? ? ?2016-03 ? ? ? ? ? ? ? 20
4 ? ? ? ? ? ?2016-04 ? ? ? ? ? ? ? ?null
5 ? ? ? ? ? ?2016-05 ? ? ? ? ? ? ? ?30
6 ? ? ? ? ? ?2016-06 ? ? ? ? ? ? ? ?null
期望排序為
id? ? ? ? created_at? ? ? ? ? real_name
6? ? ? ? ? ? 2016-06? ? ? ? ? ? ? ? null
4? ? ? ? ? ? 2016-04? ? ? ? ? ? ? ? null
2? ? ? ? ? ? 2016-02? ? ? ? ? ? ? ? null
5? ? ? ? ? ? 2016-05? ? ? ? ? ? ? ? 30
3? ? ? ? ? ? 2016-03? ? ? ? ? ? ? ? 20
1 ? ? ? ? ? ?2016-01 ? ? ? ? ? ? ? ?40
如果只用 ->orderBy('real_name','asc')->orderBy('created_at','desc')結果為
id? ? ? ? created_at? ? ? ? ? real_name
6? ? ? ? ? ? 2016-06? ? ? ? ? ? ? ? null
4? ? ? ? ? ? 2016-04? ? ? ? ? ? ? ? null
2? ? ? ? ? ? 2016-02? ? ? ? ? ? ? ? null
1? ? ? ? ? ? 2016-01? ? ? ? ? ? ? ? 40
5? ? ? ? ? ? 2016-05? ? ? ? ? ? ? ? 30
3? ? ? ? ? ? 2016-03? ? ? ? ? ? ? ? 20
因為real_name不同 所以有real_name的created_at排序沒有生效
二、解決辦法:
->orderBy(\DB::raw('ISNULL(real_name)'),'desc')->orderBy('created_at','desc')
使用sql判斷real_name是否為空,如果為空就是1,不為空就是0;這樣real_name就只有1和0,是0 的排后面(因為0代表real_name不為空),是1的排前面。
相當于:
id? ? ? ? created_at? ? ? ? ? real_name
6? ? ? ? ? ? 2016-06? ? ? ? ? ? ? ? 1
4? ? ? ? ? ? 2016-04? ? ? ? ? ? ? ? 1
2? ? ? ? ? ? 2016-02? ? ? ? ? ? ? ? 1
5? ? ? ? ? ? 2016-05? ? ? ? ? ? ? ? 0
3? ? ? ? ? ? 2016-03? ? ? ? ? ? ? ? 0
1 ? ? ? ? ? ?2016-01 ? ? ? ? ? ? ? ?0
結束。