如何将mysql转换为laravel雄辩的左联接?

时间:2019-04-07 14:44:01

标签: laravel laravel-5 eloquent

这样的MySQL查询:

SELECT a.id, a.name, b.TotalMeal, c.TotalCollection
FROM users a
LEFT JOIN (
    SELECT user_id, SUM( breakfast + dinner + lanch ) AS TotalMeal
    FROM meals
    GROUP BY user_id) b ON a.id = b.user_id
LEFT JOIN (
    SELECT user_id, SUM( amount ) AS TotalCollection
    FROM collections
    GROUP BY user_id) c ON a.id = c.user_id
LIMIT 0, 30

我想雄辩地将其转换为Laravel,但我感到困惑。我有三张桌子。例如-users(id,name,email ..),饭食(user_id,breakfast,lanch,dinner)和collections(user_id,amount)。

1 个答案:

答案 0 :(得分:0)

有一个小技巧,它使用withCount()选择可以在您的方案中使用的相关表的总和:

User::query()
    ->select([
        'id',
        'name',
    ])
    ->withCount([
        'meals as total_meals' => function ($query) {
            $query->select(DB::raw('SUM(breakfast + dinner + lunch)'));
        },
        'collections as total_collections' => function ($query) {
            $query->select(DB::raw('SUM(amount)'));
        },
    ])
    ->get();

在此查询中,withCount将为您执行联接。