can a Product only have 1 Color? if yes, you should have color_id in the Products table
Nov 4, 2017
7
Level 1
Help with building a query to retrieve colors
I have the following db structure:
products: id, product_id, name, desc, etc...
categories: id, name, slug
product_category: product_id, category_id
product_colors: id, product_id, hex, name
I also have the route: /category/{slug}, where a user sees all products under a category, with a sidebar for filtering them by price and other categories. What is the best way to retrieve all product colors specifically the products that were loaded under a category, distinct values also, so there won't be duplicate colors.
Query to retrieve products:
$products = Product::whereHas('categories', function($q) {
$q->whereIn('id', [1, 2, 4, 6]);
});
Product.php:
public function categories() {
return $this->belongsToMany(Category::class, 'product_category');
}
public function colors() {
return $this->hasMany(ProductColor::class);
}
Category.php
public function product() {
return $this->belongsToMany(Product::class, 'product_category');
}
ProductColor.php
public function product() {
return $this->belongsTo(Product::class);
}
Level 1
$productIds = array_column($products->toArray(), 'id');
$productColors = ProductColor::whereIn('product_id', $productIds)->groupBy('id')->get();
You can also change group by column to match your needs.
Please or to participate in this conversation.