jeudi 26 novembre 2020

Filter data based on relation laravel

I have product table like:

id | Title     | Price

1    Title 1     5000
2    Product 2   7000

this is related to product_attribute table

id | product_id | attribute_id | attribute_name | value
 1     1              5             Color         Red
 2     1              6             Size           XL
 3     2              5             Color         Green

in product model there is following relation:

 public function attributes()
    {
        return $this->hasMany(ProductsAttribute::class, 'product_id ');
    }

In controller method :

public function search(Request $request)
    {  
     $attributes=$request->attributes;
     foreach($attributes as $attr)
          {
            $attribute_id=$attr['attribute_id'];
            $attribute_value=$attr['value'];
          }

     return product::with('attributes')
            ->whereHas('attributes', function ($query) use ($attribute_id,$attribute_value)  {
                $query->where('attribute_id', $attribute_id);
                $query->where('value', $attribute_value);
            })->paginate(10);
    }

Issue is in my foreach loop i'm getting multiple attribute_id and attribute_value but in the query i can pass only single value of attribute_id and value. I want to fetch all the products where attribute id and attribute value matches. Any help is highly appreciated.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire