Search code examples
sqllaravelselecteloquentdistinct-on

How to use DISTINCT ON in Laravel Eloquent


Here is my full SQL Statement:

SELECT DISTINCT ON (hbg.group_id)
    hbg.group_id,
    hbg.id AS id,
    hbg.group_name,
    hbg.group_description,
    hbg.group_type_id,
    hbgt.group_type_name,
    hbg.category_id,
    hbg.effective_start_datetime,
    hbg.created_by,
    hbg.created_datetime,
    hbg.archived_by,
    hbg.archived_datetime
FROM hms_bbr_group hbg
LEFT JOIN hms_bbr_group_type hbgt
    ON hbg.group_type_id = hbgt.group_type_id
ORDER BY
    hbg.group_id,
    hbg.id DESC;  

I am trying to turn this statement into Laravel Eloquent code:

public function fetchgroup(){
    $all_groups = HmsBbrGroup::leftJoin('hms_bbr_group_type', 'hms_bbr_group.group_type_id', '=', 'hms_bbr_group_type.group_type_id')
                               ->distinct('group_id')
                               ->orderBy('group_id', 'ASC', 'id', 'DESC')->get();
    return response()->json([
        'all_groups'=>$all_groups,
    ]);
}
  • I have read that eloquent somehow does not support DISTINCT ON so I cannot just simply do distinctOn('group_id')
  • If this is the case, is there any way to modify the select inside the function to use DISTINCT ON?

Solution

  • Use DB::raw inside your select statement or add a selectRaw at the end. Here are some options:

    ->select(
        DB::raw('distinct on (hbg.group_id)'),
        'hbg.group_id',
        ...)
    

    ->select(...)
    ->selectRaw('distinct on (hbg.group_id)')
    

    ->selectRaw('DISTINCT ON (hbg.group_id)
        hbg.group_id,
        hbg.id AS id,
        hbg.group_name,
        hbg.group_description,
        hbg.group_type_id,
        hbgt.group_type_name,
        hbg.category_id,
        hbg.effective_start_datetime,
        hbg.created_by,
        hbg.created_datetime,
        hbg.archived_by,
        hbg.archived_datetime
    ')