How to sort NULL values last using Eloquent in Laravel

前端 未结 8 1272
终归单人心
终归单人心 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:14

    I ran into this problem recently using Laravel 5.6, where junkystu answer was perfect for me. However our testing framework uses sqlite, so tests were constantly returning a 500 error.

    This is what we came up with, which should be slightly more agnostic of a DB driver.

    Ascending

    $query->orderBy(DB::raw('column_to_sort IS NULL, column_to_sort'), 'asc');
    

    Descending

    $query->orderBy(DB::raw('column_to_sort IS NOT NULL, column_to_sort'), 'desc');
    

提交回复
热议问题