如何在复杂的连接和组上有效地使用laravel 5.5 eloquent

时间:2018-02-09 03:51:41

标签: php mysql laravel eloquent laravel-5.5

我有这个成功在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;

如何转换该查询以便我可以使用laravel eloquent或查询构建器?

2 个答案:

答案 0 :(得分:0)

您可以使用DB::select运行复杂的原始SQL

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

答案 1 :(得分:0)

这是我使用查询构建器未经测试的尝试:

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