我正在开发自定义电子商务解决方案。我要指出的是,我无法获得具有其属性和属性值(按名称分组)的产品。 例如,用户位于category_01中,这里有5个产品。我想向他显示可用值的属性过滤器。但是只有这5个产品的属性和值。我可以获取分组的属性标题,但是我不知道如何获取分组的属性值。
CREATE TABLE `shop_products` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`status` tinyint(1) unsigned NOT NULL DEFAULT '1',
`title` varchar(255) COLLATE utf8_unicode_ci,
`sku` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`price` double(10,4) unsigned NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `shop_products_properties` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`product_id` int(10) unsigned NOT NULL,
`title` varchar(255) COLLATE utf8_unicode_ci,
`deleted` tinyint(1) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `product_id_foreign` (`product_id`),
CONSTRAINT `product_id_foreign` FOREIGN KEY (`product_id`)
REFERENCES `shop_products` (`id`) ON DELETE CASCADE
)
CREATE TABLE `shop_products_properties_values` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`property_id` int(10) unsigned NOT NULL,
`value` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`deleted` tinyint(1) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `values_property_id_foreign` (`property_id`),
CONSTRAINT `values_property_id_foreign` FOREIGN KEY (`property_id`)
REFERENCES `shop_products_properties` (`id`) ON DELETE CASCADE
)
我正在使用Laravel,因此我获得了具有hasMany属性和hasMany值的过滤产品。效果很好,但现在我需要按标题对属性进行分组,并按值对属性值进行分组。
示例:
1.Product
shop_products: T-shirt
shop_products_properties: Color, Size, Material
shop_products_properties_values: Black, Red, White, XS, S, M, Cotton
2.Product
shop_products: Hoodie
shop_products_properties: Color, Size
shop_products_properties_values: Red, Green, White, M, L, XL
我需要得到如下结果:
Colors: Black, Red, White, Green, White
Sizes: XS, S, M, L, XL
Materials: Cotton
我不知道是否有可能创建mysql查询以获得此结果,还是我应该过滤和自定义集合...我将不胜感激
答案 0 :(得分:1)
假设我已经正确解释了您的数据结构,那么该查询将满足您的要求。
SELECT p.title, GROUP_CONCAT(DISTINCT v.value ORDER BY v.value) AS `values`
FROM shop_products_properties p
LEFT JOIN shop_products_properties_values v
ON v.property_id=p.id
GROUP BY p.title
输出:
title values
Color Black,Green,Red,White
Material Cotton
Size L,M,S,XL,XS