【问题标题】:Laravel if request not empty add orWhereLaravel 如果请求不为空添加 orWhere
【发布时间】:2018-12-02 04:21:00
【问题描述】:
public function index(Request $request) {
    if ($request->has('deleted')) {
        $assistants = Assistant::onlyTrashed()->where(1);
        if ($request->has('firstName'))
            $assistants = $assistants->orWhere('firstname', 'LIKE', $request->firstName.'%');
        if ($request->has('lastName'))
            $assistants = $assistants->orWhere('lastname', 'LIKE', $request->lastName.'%');
        if ($request->has('email'))
            $assistants = $assistants->orWhere('email', 'LIKE', $request->email.'%');
    } else {
        $assistants = Assistant::all()->where(1);
        if ($request->has('firstName'))
            $assistants = $assistants->orWhere('firstname', 'LIKE', $request->firstName.'%');
        if ($request->has('lastName'))
            $assistants = $assistants->orWhere('lastname', 'LIKE', $request->lastName.'%');
        if ($request->has('email'))
            $assistants = $assistants->orWhere('email', 'LIKE', $request->email.'%');
    }

    return $this->showAll($assistants);
}

我正在尝试检查 firstName、lastName 或 email 是否不为空,请使用 LIKE 命令添加到查询。

但它返回一个错误:

类型错误:函数的参数太少 Illuminate\Support\Collection::where(), 1 次通过

在 Laravel 5.6 中。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    你有多个问题。

    1. where(1) 不是有效的查询生成器调用。你似乎也不需要这个。

    2. 您不需要重复所有这些request->has() 调用,将它们放在 if ... else ... 下方。

    3. Assistants::all() 将实际运行查询并返回集合中的所有行。使用Assistants::query() 返回一个查询生成器实例。

    【讨论】:

    • 我应该写原始查询吗?我找不到 ::query()
    猜你喜欢
    • 1970-01-01
    • 2021-01-15
    • 2019-07-23
    • 1970-01-01
    • 2019-03-10
    • 2017-09-05
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    相关资源
    最近更新 更多