在Laravel合并3个查询?

时间:2017-08-01 09:13:37

标签: php laravel

我想知道是否有办法在Laravel中合并这些3个查询,同时还要检查Auth :: check()?

git cherry-pick

2 个答案:

答案 0 :(得分:0)

是的,我们可以在单个数据库查询中执行此操作,

$banCountQuery = GameBan::where(function ($query) use($request) {
    $query->where('ban_type', 'ip_ban');
    $query->orWhere('ban_value', $request->ip());
});

if (Auth::check()) {
    $banCountQuery->where(function ($query) use ($request) {
        $query->where('ban_type', 'user_ban');
        $query->orWhere('ban_value', Auth::user()->username);
    })->where(function ($query) use ($request) {
        $query->where('ban_type', 'machine_ban');
        $query->orWhere('ban_value', Auth::user()->username);
    });
}
$banCount = $banCountQuery->whereRaw('expires_at > now()')->count();

答案 1 :(得分:0)

$banCount = GameBan::where('ban_type', 'ip_ban')->where('ban_value', $request->ip())->whereRaw('expires_at > now()')
    ->when(Auth::check(), function ($query) {
        $query->orWhere('ban_type', 'user_ban')->where('ban_value', Auth::user()->username)->whereRaw('expires_at > now()');
        $query->orWhere('ban_type', 'machine_ban')->where('ban_username', Auth::user()->username)->whereRaw('expires_at > now()');
    })->count();