如何在 laravel 中使用带有 groupby 的 Laravel 子查询和 where

How to do this in laravel using Laravel subquery with groupby and where

select * from `eplan_vacancy` where `reference_id` in 
    (select `eplan_ep_details`.`reference_id` 
        from `eplan_ep_details` 
        inner join `eplan_court_cases` on `eplan_ep_details`.`reference_id` = `eplan_court_cases`.`reference_id` 
        where `ep_cc_status` = 1 
        group by `eplan_court_cases`.`reference_id`) 
and `is_form_submitted` = 1 
and `st_code` in ('U05', 'S13', 'S01') 
group by `reference_id` 
order by `created_at` desc

您可以使用闭包作为 whereIn 方法的第二个参数。

whereIn($column, $values, $boolean = 'and', $not = false)
$return = DB::table('eplan_vacancy')
    ->whereIn('reference_id', function ($query) {
        return $query->select('eplan_ep_details.reference_id')
            ->from('eplan_ep_details')
            ->join('eplan_court_cases', 'eplan_ep_details.reference_id', '=', 'eplan_court_cases.reference_id')
            ->where('ep_cc_status', 1)
            ->groupBy('eplan_court_cases.reference_id');
    })
    ->where('is_form_submitted', 1)
    ->whereIn('st_code', ['U05', 'S13', 'S01'])
    ->groupBy('reference_id')
    ->orderBy('created_at', 'desc');

dd($return->toSql());

结果

select * from `eplan_vacancy` where `reference_id` in 
    (
        select `eplan_ep_details`.`reference_id` 
        from `eplan_ep_details` 
        inner join `eplan_court_cases` on `eplan_ep_details`.`reference_id` = `eplan_court_cases`.`reference_id` 
        where `ep_cc_status` = ? 
        group by `eplan_court_cases`.`reference_id`
    ) 
and `is_form_submitted` = ? 
and `st_code` in (?, ?, ?) 
group by `reference_id` 
order by `created_at` desc

这是一个完整的 eloqent 查询,您可以使用它来生成上述查询,这里我使用了您需要根据您的模型名称更改的模型。

EplanVacnacy:table "eplan_vacancy"

的模型
$result = EplanVacnacy::whereIN('reference_id',function($q){
            $q->from('eplan_ep_details')
            ->select('eplan_ep_details.reference_id')
            ->innerJoin('eplan_court_cases','eplan_ep_details.reference_id','=','eplan_court_cases.reference_id')
            ->where('eplan_ep_details.ep_cc_status',1)
            ->groupBy('eplan_court_cases.reference_id')
            ->get();
            return $q;
        })
        ->where('is_form_submitted',1)
        ->whereIN('st_code',['U05', 'S13', 'S01'])
        ->groupBy('reference_id')
        ->orderBy('created_at','desc')
        ->get();