How to sort NULL values last using Eloquent in Laravel

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

    Just add a minus sign to field and change order to DESC.

    $q->orderBy(\DB::raw('-`sortOrder`'), 'desc');
    
    0 讨论(0)
  • 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');
    
    0 讨论(0)
提交回复
热议问题