简体   繁体   中英

How to effectively using laravel 5.5 eloquent on complex join and group

I have this query that successfully run on mysql workbench:

SELECT
    any_value(u.username),
    any_value(b.name),
    any_value(gc.visit_cycle_id),
    any_value(gc.group_number),
    any_value(dc.total_customer),
    count(*) as total_day
FROM
    trackgobackenddb.group_cycles gc
LEFT JOIN (
    SELECT 
        any_value(dc.group_cycle_id) as group_cycle_id,
        count(*) as total_customer
    FROM
        trackgobackenddb.destination_cycles dc
    GROUP BY dc.group_cycle_id
) dc ON dc.group_cycle_id = gc.id
LEFT JOIN visit_cycles vc ON gc.visit_cycle_id = vc.id
LEFT JOIN users u ON vc.user_id = u.id
LEFT JOIN branches b ON vc.branch_id = b.id
GROUP BY gc.visit_cycle_id, gc.group_number;

How to convert that query so I can use laravel eloquent or query builder?

You can use DB::select to run complex raw SQL

$sql = "";
$data = DB::select($sql);

Here's my untested attempt using the query builder:

DB::table('group_cycles AS gc')
    ->leftJoin('destination_cycles AS dc', function ($join) {
          $join->on('dc.group_cycle_id', '=', 'gc.id')
               ->select(['dc.group_cycle_id AS group_cycle_id', DB::raw('select count(*) AS total_customer')]);
    })
    ->leftJoin('visit_cycles AS vc', function ($join) {
         $join->on('gc.visit_cycle_id', '=', 'vc.id');
    })
    ->leftJoin('users AS u', function ($join) {
         $join->on('vc.user_id', '=', 'u.id');
    })
    ->leftJoin('branches AS b', function ($join) {
         $join->on('vc.branch_id', '=', 'b.id');
    })
    ->groupBy('gc.visit_cycle_id', 'gc.group_number')
    ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM