雄辩的带有GROUP BY和SUM的SQL请求

时间:2019-05-09 08:25:18

标签: sql laravel eloquent

我只想在laravel应用程序中发出一个简单的sql请求。

我对口才aha不太满意。

这是我想雄辩地提出的SQL请求:

select user_id, project_id, sum(hours)
FROM time_entries
WHERE spent_on BETWEEN '2018-04-10' AND '2018-12-10'
GROUP BY user_id, project_id

我一直在尝试类似的东西:

TimeEntries::whereBetween('spent_on', [($request->input('debut')), ($request->input('fin'))])->groupBy('user_id')->sum('hours');

(但您会看到它绝望)

4 个答案:

答案 0 :(得分:0)

使用selectRaw()

TimeEntries::whereBetween('spent_on', [($request->input('debut')), ($request->input('fin'))])->groupBy(['user_id', 'project_id'])->selectRaw('user_id , project_id, sum(hours) as sum')->get();

答案 1 :(得分:0)

您可以使用Eloquent的selectRaw功能,  像这样:

TimeEntries::selectRaw('user_id, project_id, sum(hours)')
    ->whereBetween(
        'spent_on',
        [ ($request->input('debut')), ($request->input('fin')) ]
    )
    ->groupBy('user_id', 'project_id');

但是请注意,不要绑定selectRaw字符串参数中的变量,这可能会导致SQL注入问题,因为它绕过了转义检查

答案 2 :(得分:0)

下面的查询将起作用:

$query = TimeEntries::query();
$query->selectRaw('user_id', 'project_id', sum(hours))
->whereRaw("spent_on >= '2018-04-10' and spent_on <= '2018-12-10'")
->groupBy('user_id')
->groupBy('project_id');

$result = $query->get();

答案 3 :(得分:-1)

  

Model-> select(DB :: raw('user_id,project_id,   SUM(hours)')-> wherebetween ...