【问题标题】:Eloquent Conditional orWhere雄辩的条件或在哪里
【发布时间】:2019-08-25 09:46:50
【问题描述】:

我有一个搜索产品的搜索框。我希望它工作的方式是,如果我搜索产品 name 并且它存在,那么它会返回与搜索匹配的产品。如果搜索与我希望它然后搜索产品descriptions的任何产品的名称不匹配。这是我尝试过的

$products = Product::where(function ($query) use ($terms) {
            foreach ($terms as $term) {
                // Loop over the search terms
                $query->orWhere('name', 'like', '%' . $term . '%');
            }
        })->latest()->paginate($productsPerPage);

        if(empty($products)){
            $products = Product::where(function ($query) use ($terms) {
              foreach ($terms as $term) {
                  $query->orWhere('description', 'like', '%' . $term . '%');
              }
          })->latest()->paginate($productsPerPage);
        }

但这不起作用,如果搜索包含产品描述,它不会返回任何结果。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    empty($products) 不起作用,因为paginate 调用总是返回一个LengthAwarePaginator 实例,因此不是empty

    可以使用以下代码:

       $products = Product::where(function ($query) use ($terms) {
            foreach ($terms as $term) {
                // Loop over the search terms
                $query->orWhere('name', 'like', '%' . $term . '%');
            }
        })->latest()->paginate($productsPerPage);
    
        if ($products->total() == 0) {
            $products = Product::where(function ($query) use ($terms) {
                foreach ($terms as $term) {
                    $query->orWhere('description', 'like', '%' . $term . '%');
                }
            })->latest()->paginate($productsPerPage);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-20
      • 2014-04-14
      • 2017-08-22
      • 2019-09-23
      • 1970-01-01
      • 2021-12-18
      • 2013-05-31
      • 2015-08-08
      相关资源
      最近更新 更多