dpizd08264 2017-11-04 12:20
浏览 28

构建查询以检索可用的产品颜色

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: product_id, color_id
product_sizes: product_id, size_id
colors: id, value, hex
sizes: id, value

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:

Product::whereHas('categories', function ($q) use ($cat_ids) {
        return $q->whereIn('id', $cat_ids);
    })->with(['colors', 'sizes', 'brand'])->get();

EDIT: Retrieving colors and sizes:

$sizes = collect($products->pluck('sizes'))->flatten()->pluck('value', 'id');
$colors = collect($products->pluck('colors'))->flatten()->pluck('value', 'id');

Product.php:

public function categories() {
    return $this->belongsToMany(Category::class, 'product_category');
}

public function colors() {
    return $this->belongsToMany(Color::class, 'product_colors');
}

public function sizes() {
    return $this->belongsToMany(Size::class, 'product_sizes');
}

Category.php

public function products() {
    return $this->belongsToMany(Product::class, 'product_category');
}

Color.php

public function products() {
    return $this->belongsToMany(Product::class, 'product_colors');
}

Size.php

public function products() {
    return $this->belongsToMany(Product::class, 'product_sizes');
}
  • 写回答

2条回答 默认 最新

  • douao3063 2017-11-04 13:12
    关注

    Here's a non-collection oriented method: loop through the products in a category, calling the color function. Add each result to an array. Once done, remove duplicates.

    This will accomplish what you asked, but if you are looking to have the original products still attached to the colors (basically a different returned data structure), you'll need to specify what it should look like.

    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序