How to sort NULL values last using Eloquent in Laravel

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

    In Laravel 5.2 or higher just call orderByRaw. You even able to sort through aggregated value rather than a column. In the following example max_st can be null if there is no submodels.

    Model::where('act', '2')
        ->leftJoin('submodels', 'model.id', '=', 'submodels.model_id')
        ->select('models.*', DB::raw('MAX(submodels.st) as max_st')),
        ->orderByRaw('max_st DESC NULLS LAST');
    

提交回复
热议问题