2014-12-26 95 views
0

我对产品和购物车下表:购物车 - multple属性值

//产品表

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 

所以:

  • 客户希望产品1在黑色si泽小号
  • 客户希望产品1在红色大小为M

一种产品可以包含多个属性的值。

通过在车与AJAX-> JSON将产品我有以下数据:

- productid 
- number 
- attribute= array( // example: color 
    attribute_id 
    value_id 
) 
- attribute= array( // example: size 
    attribute_id 
    value_id 
) 

随着其查询(PDO)1可以看到,如果该组合已经存在?如果存在,我想更改此产品的编号

在'How to find all the products with specific multi attribute values'处,它们使用EXISTS。 我如何做到这一点与PDO和无限的属性(可以有更多的只有颜色和大小,但不是每个产品都有属性)。

回答

0

“古典”SQL方法将要求您在每个属性过滤器上执行JOINsub-query。 因此,如果您需要通过5个过滤器(属性值)查找产品,则需要使用5个JOIN或子查询创建一个SQL查询。与问题中相同,您发布了一个链接。

根据您的猜测,这根本无法扩展。

所以,我想提供一个不同的,但有点“haskish”的方式。 您可以在products_attribute_values表的查询,并得到对像:

ProductIDHow many attributes/filters this products match

下面是一个查询:

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 

一般来说,你可以使用这个attributes_matching值作为搜索排名的价值,您可以按其筛选&筛选。 例如,在上面的示例中,如果没有与所有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