Laravel 5.4 查询生成器使用 orWhere 子句时缺少参数 2

Posted

技术标签:

【中文标题】Laravel 5.4 查询生成器使用 orWhere 子句时缺少参数 2【英文标题】:Laravel 5.4 query builder Missing argument 2 when using orWhere clause 【发布时间】:2018-03-07 03:43:03 【问题描述】:

谁能告诉我为什么会出现这个错误以及如何解决它。

    $lastDayPreviousMonth = date("Y-m-d", strtotime("last day of previous month"));
    $firstDayPreviousMonth = date("Y-m-d", strtotime("first day of previous month"));

    $query = DB::table('employees')
        ->where('Emp_ClientId', '=', $clientId)
        ->where('Emp_StatusId', 1)
        ->orWhere(function ($query, $firstDayPreviousMonth, $lastDayPreviousMonth)
            $query->where('Emp_DateSuspTerm', '>=', $firstDayPreviousMonth)
                ->where('Emp_DateSuspTerm', '<=', $lastDayPreviousMonth)
                ->where('Emp_ClientId', '=', $clientId);
        )
        ->count();

运行时出现以下错误

缺少 App\Http\Models\Employees::App\Http\Modelsclosure() 的参数 2

我认为这与我传递给 orWhere 子句的 firstdaypreviousmonth 和 lastdaypreviousmonth 参数有关 - 如果我把它拿出来,我会得到未定义的变量。

【问题讨论】:

【参考方案1】:

你可以使用 use 关键字来使用闭包

$query = DB::table('employees')
            ->where('Emp_ClientId', '=', $clientId)
            ->where('Emp_StatusId', 1)
            ->orWhere(function ($query) use($firstDayPreviousMonth, $lastDayPreviousMonth,$clientId)
                $query->where('Emp_DateSuspTerm', '>=', $firstDayPreviousMonth)
                    ->where('Emp_DateSuspTerm', '<=', $lastDayPreviousMonth)
                    ->where('Emp_ClientId', '=', $clientId);
            )
            ->count();

【讨论】:

我会在计时器允许的时候:)

以上是关于Laravel 5.4 查询生成器使用 orWhere 子句时缺少参数 2的主要内容,如果未能解决你的问题,请参考以下文章