【问题标题】:Having another Where Filter on Laravel在 Laravel 上有另一个 Where 过滤器
【发布时间】:2017-12-06 21:44:03
【问题描述】:

我正在尝试进行搜索,并且只想返回状态为 1,4 的用户。虽然当我尝试使用它时,它会全部抓取并忽略我最后的位置。

$officiants = Officiant::where('status',1)
                        ->where('email', 'like',  '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->whereIn('status', [1,4])
                        ->get();

我也试过

$officiants = Officiant::where('status',1)
                        ->where('email', 'like',  '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->orWhere('lname', 'like', '%'.$item.'%')
                        ->where('status', 1)
                        ->where('status', 4)
                        ->get();

【问题讨论】:

    标签: php laravel laravel-5 laravel-4


    【解决方案1】:

    问题是你需要了解 Laravel 中 where 链接和 orWhere 链接是如何工作的。

    当您说$query->where(..a..)->orWhere(..b..)->where(..c..)->orWhere(..d..) 时,它的计算结果为:(a || (b && c) || d)。您可能打算使用((a || b) && (c || d)) 或者您可能打算使用((a && c) || b || d)。这就是为什么当您需要高级 where 子句时,请使用 parameter grouping

    【讨论】:

      【解决方案2】:

      你需要这样的东西:

      $officiants = Officiant::where('status',1)
          ->where(function($query) use($item){
              $query->where('email', 'like',  '%'.$item.'%')
                  ->orWhere('lname', 'like', '%'.$item.'%')
                  ->orWhere('lname', 'like', '%'.$item.'%')
          })
              ->whereIn('status', [1,4])
              ->get();
      

      注意:这未经测试

      【讨论】:

        【解决方案3】:

        我刚刚想通了

           $officiants = Officiant::where('status', 1)
                                            ->orWhere('status', 4)
                                            ->where(function ($query) use ($item) {
                                              $query->where('email', 'like',  '%'.$item.'%')
                                                    ->where('lname', 'like', '%'.$item.'%')
                                                    ->where('lname', 'like', '%'.$item.'%');
                                            })->get();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-08-02
          • 2018-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-17
          • 1970-01-01
          • 2021-09-26
          相关资源
          最近更新 更多