A
A
Andrey Boychenko2018-12-17 17:23:28
Laravel
Andrey Boychenko, 2018-12-17 17:23:28

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

And I will use the with method, I still cannot pass the argument to attrs
ModelProduct::where('category', 3)->with('attrs'); (After all, I don’t have the ability to pass an argument, right?)
In general, I’m asking for help, how to build a complex query with a many-to-many relationship, so that I can filter products by the values ​​of the product table itself, or only by the values ​​of the table associated with the products , products_attributes or attributes?
Thanks for the help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Boychenko, 2018-12-17
@Ka4_Piton

In general, the solution is quite simple. Add the following to the request

$products->WhereHas('attrs', function($q){
                $q->where('value', '3' );
            });

Ultimately the query that solves my problem will look like this:
ModelProduct::whereIn('category',$cats)->whereHas('attrs', function($q){
            $q->where('column', 'value');
        })->latest()->get();

It is not necessary to write withPivot in relation to attrs, you can do this
public function attrs($q)
    {
        return $this->belongsToMany('\App\Models\ModelAttributes','products_attributes','product_id','attribute_id')->withPivot('value');
    }

can it be like this
public function attrs($q)
    {
        return $this->belongsToMany('\App\Models\ModelAttributes','products_attributes','product_id','attribute_id');
    }

But keep in mind, if you want to access the properties of the intermediate model, then you need to specify withPivot('the fields you want to access') in the relation.
I'm very glad that I found the solution myself, but the toaster is still a wonderful, convenient and useful resource. I hope it will be useful to someone.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question