Skip to content
Advertisement

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

Advertisement

Answer

You can use closure as the second parameter of the whereIn method.

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());

Result

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
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement