How to sort NULL values last using Eloquent in Laravel

前端 未结 8 1252
终归单人心
终归单人心 2020-12-08 14:29

I\'ve got a many to many relationship between my employees and groups table. I\'ve created the pivot table, and all is working correctly with that. However, I\'ve got a sort

8条回答
  •  無奈伤痛
    2020-12-08 15:04

    A workaround for PostgreSQL

    For numeric types:

    DB::table('t')
        ->select(['id', 'val'])
        ->orderBy(DB::raw("coalesce(val, 0)"), 'desc')
    

    For text types:

    orderBy(DB::raw("coalesce(val, '')"), 'desc')
    

    The trick is to replace NULL values in the sorting column to zero (or empty string) so that it could be sorted as an ordinary integer (or text) value.

提交回复
热议问题