代码之家  ›  专栏  ›  技术社区  ›  Nevermore

Laravel if请求不为空,添加或位置

  •  0
  • Nevermore  · 技术社区  · 6 年前
    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命令添加到查询中。

    但它返回一个错误:

    类型错误:函数的参数太少 照明\支持\集合::Where(),1传递

    在Laravel 5.6.

    1 回复  |  直到 6 年前
        1
  •  1
  •   Devon Bessemer    6 年前

    你有很多问题。

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

    2. 你不需要重复所有这些 request->has() 打电话,把他们放在if…否则…

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