2014-12-26 94 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