产品过滤器

时间:2018-01-14 14:53:31

标签: php laravel laravel-5 laravel-eloquent

我有查询过滤器:

 public function filter(Request $request)
{

  $category_id = $request->category;
  $brand_id = $request->brand;
  $filters = $request->filters;

  if($brand_id == null){
    $products = Products::with('brand')->whereHas('category',function($q) use($category_id){
      $q->where('category_id', $category_id);
    })->whereHas('filters',function($q) use($filters){
      $q->where('filter_id', $filters);
    })->paginate(9);
  }else{
    $products = Products::with('brand')->where('brand_id',$brand_id)->whereHas('category',function($q) use($category_id){
      $q->where('category_id', $category_id);
    })->whereHas('filters',function($qw) use($filters){
      $qw->where('filter_id', $filters);
    })->paginate(9);
  }

  //Брэнды всех товаров
  $Brands = array();
  foreach ($products as $product) {
    if(!in_array($product->brand, $Brands)){
      array_push($Brands, $product->brand);
    }
  }

  return response()->json(['products' => $products,'brands' => $Brands]);
}

我只收到第一个产品的回复,但我需要从列表中获取至少包含一个过滤器的所有产品。我该怎么办?

2 个答案:

答案 0 :(得分:1)

在查询产品时使用whereIn()函数而不是where()

答案 1 :(得分:1)

只是一个小型重构+我不确定你是否收到一系列过滤器或只是一个id。如果您需要超过1个ID,请使用whereIn

如果您想让它更清洁,您可以为过滤器和品牌创建雄辩的范围。

public function filter(Request $request)
{
  $categoryId = $request->category;
  $brandId = $request->brand;
  $filters = $request->filters;

  $query = Products::with('brand');

  if ($brandId) {
    $query = $query->where('brand_id', $brandId);
  }

  if ($filters) {
    $query = $query->whereHas('filters', function($q) use ($filters) {
        // If you have more than one filter id, use whereIn
        // $q->where('filter_id', $filters);
        $q->whereIn('filter_id', (array) $filters);
    });
  }

  if ($categoryId) {
    $query = $query->whereHas('category', function($q) use ($categoryId) {
        $q->where('category_id', $categoryId);
    });
  }

  $products = $query->paginate(9);

  $brands = $products->total() > 0 ? $products->items()->pluck('brand')->all() : [];

  return response()->json(compact('products', 'brands'));
}