Laravel groupby min / max过滤分组结果

时间:2017-05-19 23:38:33

标签: php mysql database laravel laravel-5.2

我使用min()groupBy()按照我的方式运行Laravel查询:

$certificates = CertificateRecord::whereHas('learner', function($query) use($user) { $query->where('user_id', '=', $user->id); })
->selectRaw('*,min(type) as type')
->groupBy('certificate_template_id')
->with('issuer','certificateType')
->paginate(10);

但是当我把它加到混合中时......

->when($request->type, function ($query) use ($request) {
    return $query->where('type', '=', $request->type);
})

执行此where()时会以某种方式忽略先前分组的结果,并返回所有未分组的行。

2 个答案:

答案 0 :(得分:0)

请勿立即完成查询:

$query = $certificates = CertificateRecord::whereHas('learner', function($query) use($user) { $query->where('user_id', '=', $user->id); })
->selectRaw('*,min(type) as type')
->groupBy('certificate_template_id')
->orderBy('type')
->with('issuer','certificateType')

if ($request->status){ $query->where('status', '=', $request->status); }

$query->paginate(10);

答案 1 :(得分:0)

编辑:此处包含when条件展示位置的原始查询对我来说似乎不错。这应该过滤type字段而不影响groupBy。我想告诉你的一件事是,当设置$request->type时,结果集中只有一个type值,因此最小值将是相同的,没有任何变化。

$certificates = CertificateRecord::whereHas('learner', function($query) use($user) {
    $query->where('user_id', '=', $user->id);
})
    ->with('issuer', 'certificateType')
    ->when($request->type, function ($query) use ($request) {
        return $query->where('type', $request->type);
    })
    ->selectRaw('*, min(type) as type')
    ->groupBy('certificate_template_id')
    ->paginate(10);
$certificates = CertificateRecord::whereHas('learner', function($query) use($user) {
        $query->where('user_id', '=', $user->id);
    })
    ->with('issuer', 'certificateType')
    ->selectRaw('*, min(type) as type')
    ->groupBy('certificate_template_id')
    ->when($request->type, function ($query) use ($request) {
        return $query->having('type', '=', $request->type);
    })
    ->paginate(10);

如果这不起作用,请切换到havingRaw。

return $query->havingRaw('min(type) = ' . $request->type);