A product in Various Categories - PHP

5

Would you like to know how to link a product into several categories? For example: A shirt may be in the "Green / Blue / Yellow" categories and when I filter by category the product should appear in the "Green, Blue or Yellow" category.

I know I should use Relationship N: N, but how to apply this in PHP code? Is there another way to do it without using the N: N relationship, for example by array?

    
asked by anonymous 30.03.2015 / 20:51

1 answer

10

Do not indicate the structure of your tables, but for this purpose you should use an intermediate table that will effectively serve the purpose of relating each product to the multiple categories:

EER diagram

Inthisway,youhaveatablefortheproducts,atableforthecategoriesandatabletoestablishtherelationshipbetweenthem.

Practicalexample

Foryourcase,the"shirt" product has 3 categories, the "Green", "Blue" and "Yellow", so in the table produtos_categorias it would have three registers:

Table: Products

Table:Categories

Relationship table: Products ~ Categories

Inthisway,whenchoosingthecategoryazuliriasmakeaqueryoftype:

SELECT produtos.nome FROM produtos_categorias INNER JOIN produtos ON (produtos.id = produtos_categorias.produtos_id) INNER JOIN categorias ON ( categorias.id = produtos_categorias.categorias_id AND categorias.nome='azul' )

That returns you the products that are in the azul category.

The answer is a practical example in an abstract way, it does not reflect performance nor a correct operation for the application to be developed. It illustrates only the procedure to be taken to deal with the problem at hand.

    
30.03.2015 / 21:23