Answer the question
In order to leave comments, you need to log in
Laravel many to many?
Good evening! Please explain how I should behave with many to many relationships. Let's say I want to make a filter by products. For this I have 3 tables:
products: id, title, price, category, brand
attributes: id, title
products_attributes: id, product_id, attribute_id, value
Let's say I write ModelProduct::where('category', 3)->get ();
I will get all records with category=3 but if i need let's say get all records where category=3 and where table value products_attributes:value=1
If i write ModelProduct::where('category', 3)->attrs() ->wherePivot('value', 1)->get();
I'm getting an error because the ModelProduct builder doesn't know anything about the attrs relation. But if I define the relation as follows
public function attrs($q)
{
return $this->belongsToMany('\App\Models\ModelAttributes','products_attributes','product_id','attribute_id')->withPivot('value')->WherePivot('value',$q);
}
Answer the question
In order to leave comments, you need to log in
In general, the solution is quite simple. Add the following to the request
$products->WhereHas('attrs', function($q){
$q->where('value', '3' );
});
ModelProduct::whereIn('category',$cats)->whereHas('attrs', function($q){
$q->where('column', 'value');
})->latest()->get();
public function attrs($q)
{
return $this->belongsToMany('\App\Models\ModelAttributes','products_attributes','product_id','attribute_id')->withPivot('value');
}
public function attrs($q)
{
return $this->belongsToMany('\App\Models\ModelAttributes','products_attributes','product_id','attribute_id');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question