产品过滤器

Filters for products

我有过滤器查询:

 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]);
}

我只收到第一个产品的回复,但我需要从 list.How 中获取至少包含一个过滤器的所有产品,我可以这样做吗?

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

只是一个小的重构 + 我不确定您收到的是一组过滤器还是一个 ID。如果您需要超过 1 个 ID,请使用 whereIn.

如果你想让它更干净,你可以为过滤器和品牌创建 Eloquent 范围。

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'));
}