如何在 Laravel Eloquent 中使用 DISTINCT ON

How to use DISTINCT ON in Laravel Eloquent

这是我的完整 SQL 声明:

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;  

我正在尝试将此语句转换为 Laravel Eloquent 代码:

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

在 select 语句中使用 DB::raw 或在末尾添加 selectRaw。以下是一些选项:

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