Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1 - showing related products through pivot table

I'm stuck on this way too long to solve it myself, so here's my question:

My database is filled by clothes. I want to show related clothes based on color.

My relationships:

(Product.php)

public function colors(){
        return $this->belongsToMany('App\Color', 'colors_products', 'FK_product', 'FK_color');
    }

(Color.php)

 public function products(){
        return $this->belongsToMany('App\Product', 'colors_products', 'FK_color', 'FK_product');
    }

So every product has multiple colors. I want to show related pieces on the same page. So if I'm looking at a piece with the color "red" and "black", I want to show both related clothes labeled with "red" and/or "black". So it doesn't have to be both red AND black.

How can I get all clothes with one of the (sometimes multiple) colors like the piece i'm watching?

UPDATE

Product::with('colors')->whereIn('id', $arColors)->get(); is part of the solution. When I have a product with 2 colors (red & black) I see the related products with only black or only red. But when I watch a product with only black, the related items with multiple colors do not show.

like image 957
RW24 Avatar asked Jan 30 '26 02:01

RW24


1 Answers

NULL's answer is close. I think you want to use whereHas() for this. Given that your colors array is readily available from your active product, let's say it's called $color_ids.

To load all other products that match one of these colors, try this:

$related_products = Product::whereHas('colors', function($query) use ($color_ids) {
    $query->whereIn('id', $color_ids);
})->get();

whereIn() is documented here: http://laravel.com/docs/5.1/queries#where-clauses

whereHas() is documented here: http://laravel.com/docs/5.1/eloquent-relationships#querying-relations

like image 179
Trip Avatar answered Jan 31 '26 16:01

Trip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!