Php 购物车-多属性值
我有以下关于产品和购物车的表格: //产品表Php 购物车-多属性值,php,mysql,pdo,Php,Mysql,Pdo,我有以下关于产品和购物车的表格: //产品表 Products: id | Product_value ----------------------- 1 | Product 1 Attributes: id | Attribute_value ----------------- 1 | Color 2 | Size Attribute_values: id | Attribute_id |
Products:
id | Product_value
-----------------------
1 | Product 1
Attributes:
id | Attribute_value
-----------------
1 | Color
2 | Size
Attribute_values:
id | Attribute_id | Value_value
---------------------------------
1 | 1 | Black
2 | 1 | Red
3 | 1 | Blue
4 | 2 | S
5 | 2 | M
6 | 2 | L
7 | 2 | XL
Product_attribute_values
Product_id | Attribute_id | Value_id
--------------------------------------
1 | 1 | 1
1 | 1 | 2
1 | 1 | 3
1 | 2 | 4
1 | 2 | 5
1 | 2 | 6
1 | 2 | 7
//数据库表
Cart:
id | product_id | number_value
----------------------------------
1 | 1 | 1
2 | 1 | 1
Product_attribute_value:
Cart_id | attribute_id | value_id
--------------------------------------
1 | 1 | 1
1 | 2 | 4
2 | 1 | 2
2 | 2 | 5
因此:
- 客户需要黑色S码的产品1
- 客户想要红色尺寸M的产品1
- productid
- number
- attribute= array( // example: color
attribute_id
value_id
)
- attribute= array( // example: size
attribute_id
value_id
)
使用哪个查询(PDO)可以查看此组合是否已经存在?如果存在,我想更改此产品的编号
他们使用的“”处存在。
如何使用PDO和无限属性(颜色和大小可能不止一个,但不是每个产品都有属性)实现这一点。“经典”SQL方法将要求您在每个属性过滤器上执行连接
或子查询
。
因此,如果需要通过5个过滤器(属性值)查找产品,则需要创建一个包含5个联接或子查询的SQL查询。与问题中相同,您发布了指向的链接
你可能会猜到,这根本不是可伸缩的
所以,我想提供一种不同的,但有点“急躁”的方式。
您可以在products\u attribute\u values
表上进行查询,并获得如下配对:
ProductID
,此产品匹配多少属性/过滤器
以下是一个问题:
SELECT product_id, COUNT(*) AS `attributes_matching` FROM Product_attribute_values
WHERE
Attribute_id1=Value1 // example: color
AND
Attribute_id2=Value2 // example: size
AND
Attribute_id3=Value3 // example: for-man/women/kid
AND
Attribute_id4=Value4 // example: Manufacturer
AND
Attribute_id5=Value5 // example: Material
GROUP BY product_id
通常,您可以使用此属性\u匹配值作为搜索排名值,您可以根据它进行排序和筛选。
例如,在上面的示例中,如果没有与所有5个过滤器匹配,则可以显示与4个过滤器匹配的产品
如果要获得与所有5个过滤器(严格过滤)匹配的产品,只需在查询末尾添加HAVING
:
...
AND
Attribute_id5=Value5 // example: Material
GROUP BY product_id
HAVING attributes_matching=5 // 5 - number of filters in this case