lundi 13 juin 2016

Laravel - How to query when you have a many to many relationship

So I have two models: Product and Size. One product may have many sizes and one size may have many products that have that size. I made many ot many relationship between them with a product_size pivot table. Now I need to query all products that have a certain size. Here is my code:

$products = Product::where(function ($query) use ($request) {

            $minPrice = $request['min'] ? $request['min'] : null;
            $maxPrice = $request['max'] ? $request['max'] : null;
            $colors = $request['color'] ? $request['color'] : null;
            $sizes = $request['size'] ? $request['size'] : null;

            if (isset($minPrice)&& isset($maxPrice)) {
                $query->where('price', '>=', $minPrice)->where('price', '<=', $maxPrice);
            }

            if(isset($colors)) {
                foreach ($colors as $color) {
                    $query->where('color_id', '=', $color);
                }
            }

            if(isset($sizes)) {
                foreach ($sizes as $size) {
                    $query->with('sizes')->where('size', '=', $size); // Doesn't work. What is the right way?
                }
            }


        })->get();

How can I do that?

Aucun commentaire:

Enregistrer un commentaire