Laravel查询按ASC排序时null值前置,如何获取正确升序记录?
Laravel查询排序:让null值排在升序结果末尾
问题场景
执行以下Laravel查询时,atm_active_time为null的记录会排在最前面,无法实现有效时间按升序在前、null值在后的需求:
$query = Agent::where('is_super_main_agent', false) ->where('is_main_agent', false) ->orderBy('atm_active_time', 'ASC');
解决办法
以下几种方法都能实现需求:
方法1:用
orderByRaw直接写原生排序逻辑
利用SQL的IS NULL判断,让非null值优先排序,再按时间升序:$query = Agent::where('is_super_main_agent', false) ->where('is_main_agent', false) ->orderByRaw('atm_active_time IS NULL, atm_active_time ASC');逻辑说明:
atm_active_time IS NULL返回的布尔值会被转成数字,null值对应1,非null对应0,0排在1前面,所以非null记录先出现,之后再按时间升序排列。方法2:结合
DB::raw拆分排序条件
和方法1逻辑一致,只是把排序条件拆成两个orderBy:use Illuminate\Support\Facades\DB; $query = Agent::where('is_super_main_agent', false) ->where('is_main_agent', false) ->orderBy(DB::raw('atm_active_time IS NULL'), 'ASC') ->orderBy('atm_active_time', 'ASC');方法3:MySQL专属写法(用IF函数)
如果你的数据库是MySQL,也可以用IF函数来标记null值:$query = Agent::where('is_super_main_agent', false) ->where('is_main_agent', false) ->orderByRaw('IF(atm_active_time IS NULL, 1, 0), atm_active_time ASC');
内容的提问来源于stack exchange,提问作者siddharthsinh vaghela
相关产品推荐
相关产品推荐

