Domanda

Now I have 4 tables:

table categories:
-id
-category

table products:
-id
-product
-price
-image

table attributes:
-id
-attribute
-product_id

table values:
-product_id
-attribute_id
-value

And I'm querying with:

SELECT `id`, `product`, `price`, `image` FROM `products` WHERE `category_id` = $category->id

Now I got array of products for this category and need to get it's properties: next query:

SELECT `products`.`id` AS `product_id`, 
`attributes`.`attribute`, 
`values`.`value` 
FROM `products` LEFT JOIN `attributes` ON (`attributes`.`product_id` = `products`.`id`) 
LEFT JOIN `values` ON (`values`.`product_id` = `products`.`id` 
AND `values`.`attribute_id` = `attributes`.`id`) 
WHERE `products`.`id` IN ($ids)

And it's get the attributes with values but I'm wondering about one thing: If it's possible to get rid of 'product_id' column in table attributes and get attributes and values without that column? Now it's a whole bunch of duplicating attributes for example:

table attributes 
-id 1
-attribute Weight
-product_id 1

-id 2
-attribute Weight
-product_id 2

While I want just:

-id 1
-attribute Weight

sorry for my english, if some part of my post needs more explanation please let me now

È stato utile?

Soluzione

It depends if you want your attributes to be product specific, but you obviously, don't. Also, you don't need product_id in your values table, if you have it in your attributes table. So your tables make more sense if they are like:

table categories:
-id
-category

table products:
-id
-product
-price
-image
-category_id

table attributes:
-id
-attribute
-product_id

table values:
-attribute_id
-value

Actually, I would make it a lot more simple EAV:

table categories:
-id
-category

table products:
-id
-product
-price
-image
-category_id

table attributes:
-id
-product_id
-attribute
-value

And then, your query would look like:

SELECT id, product, price, image, attribute, value
FROM products
    INNER JOIN attributes ON products.id = attributes.product_id
WHERE products.category_id = :category_id

Make sure you have appropriate indexes. Also, the way you wanted to do it with selecting product ids and then putting them into IN, is a bad practice.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top