How to sort NULL values last using Eloquent in Laravel

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

    Instead of relying on an arbitrary large number you can also do:

    public function employees()
    {
        return $this
            ->hasMany('Employee')
            ->select(['*', DB::raw('sortOrder IS NULL AS sortOrderNull')])
            ->orderBy('sortOrderNull')
            ->orderBy('sortOrder');
    }
    

    It has an added benefit of being supported by SQLite.

提交回复
热议问题