Laravel 5.6其中具有If条件

时间:2018-09-20 06:22:05

标签: laravel

我在ProductRepository.php中的功能是这样的:

public function listProductsFilter($columns=[],$category=[])
    {
        $keywords = [];
       foreach($columns as $key => $value){
         $keywords[] = [$key, 'LIKE', '%'.$value.'%'];
        }

         $query=  $this->model
         ->join('category_product', 'products.id', '=', 'category_product.product_id')
          ->orderBy('name', 'asc')
         ->where('products.is_deleted', 0)
         ->Where($keywords)
         ->whereIn('category_product.category_id', $category)
         ->get();


         return $query;
    }

我添加了一个条件来检查类别是否存在。我尝试过喜欢它,但是出现了错误:

if(isset($category))
         ->whereIn('category_product.category_id', $category)

语法错误,意外的'if'(T_IF)

如何解决该错误?

1 个答案:

答案 0 :(得分:3)

    public function listProductsFilter($columns=[],$category=[])
        {
            $keywords = [];
           foreach($columns as $key => $value){
             $keywords[] = [$key, 'LIKE', '%'.$value.'%'];
            }

             $query=  $this->model
             ->join('category_product', 'products.id', '=', 'category_product.product_id')
              ->orderBy('name', 'asc')
             ->where('products.is_deleted', 0)
             ->Where($keywords);
if(isset($category))
              $query= $query->whereIn('category_product.category_id', $category);
             $query= $query->get();


             return $query;
        }