Laravel 如何将原始数据库查询转换为查询生成器

How to convert raw Database query to Query Builder in Laravel

美好的一天。请问如何将原始 sql 查询转换为 Laravel 查询生成器。原始的sql,无法分页,而且数据量很大

$cpCounsel = DB::table('cp_counsel as A')
    ->select([
        'A.enrolment_number as id',
        DB::raw('MIN(A.counsel) as counsel'),
    ])
    ->groupBy('enrolment_number');

$counsels = DB::table('cp_cases_counsel as T')
    ->joinSub($cpCounsel, 'A.id', '=', 'T.counsel_id')
    ->where('A.counsel', 'like', "%$request->search_term%")
    ->select([
        'T.counsel_id',
        'A.counsel',
        DB::raw('COUNT(T.counsel_id) as total'),
        DB::raw('SUM(if(T.court_id = 2, 1, 0)) as supreme_court_cases'),
        DB::raw('SUM(if(T.court_id = 2, 1, 0) AND if(T.counsel_role = 1, 1, 0)) as supreme_court_cases_as_lead'),
        DB::raw('SUM(if(T.court_id = 2, 1, 0) AND if(T.counsel_role = 2, 1, 0)) as supreme_court_cases_as_supporting'),
        DB::raw('SUM(if(T.court_id = 1, 1, 0)) as appeal_court_cases'),
        DB::raw('SUM(if(T.court_id = 1, 1, 0) AND if(T.counsel_role = 1, 1, 0)) as appeal_court_cases_as_lead'),
        DB::raw('SUM(if(T.court_id = 1, 1, 0) AND if(T.counsel_role = 2, 1, 0)) as appeal_court_cases_as_supporting'),
    ])
    ->groupBy('T.counsel_id', 'A.counsel')
    ->paginate(15);

我修改了@MohammedHassan 的回复。谢谢

通常,SQL 语句在 Laravel query builder 中具有等效项,当您需要使用函数时,您将语句包装在 DB::raw().

您的查询可以这样重写:

$cpCounsel = DB::table('cp_counsel as A')
    ->select([
        'A.enrolment_number as id',
        DB::raw('MIN(A.counsel) as counsel'),
    ])
    ->groupBy('enrolment_number');

$counsels = DB::table('cp_cases_counsel as T')
    ->joinSub($cpCounsel, 'A.id', '=', 'T.counsel_id')
    ->where('A.counsel', 'like', "%$request->search_term%")
    ->select([
        'T.counsel_id',
        'A.counsel',
        DB::raw('COUNT(T.counsel_id) as total'),
        DB::raw('SUM(if(T.court_id = 2, 1, 0)) as supreme_court_cases'),
        DB::raw('SUM(if(T.court_id = 2, 1, 0) AND if(T.counsel_role = 1, 1, 0)) as supreme_court_cases_as_lead'),
        DB::raw('SUM(if(T.court_id = 2, 1, 0) AND if(T.counsel_role = 2, 1, 0)) as supreme_court_cases_as_supporting'),
        DB::raw('SUM(if(T.court_id = 1, 1, 0)) as appeal_court_cases'),
        DB::raw('SUM(if(T.court_id = 1, 1, 0) AND if(T.counsel_role = 1, 1, 0)) as appeal_court_cases_as_lead'),
        DB::raw('SUM(if(T.court_id = 1, 1, 0) AND if(T.counsel_role = 2, 1, 0)) as appeal_court_cases_as_supporting'),
    ])
    ->groupBy('T.counsel_id', 'A.counsel')
    ->paginate(15);

最终使用 laravel DB joinSub 方法得到了这个