user16409170
user16409170

Reputation:

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,
    ]);
}

Upvotes: 0

Views: 2198

Answers (1)

IGP
IGP

Reputation: 15859

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
')

Upvotes: 1

Related Questions