Products and category tables. Creating relation with products and categories attributes referencing different category entities

StackOverflow https://stackoverflow.com/questions/22867468

Question

I’m trying to create an e-commerce site, a sort of a basic Alibaba. The final goal is to create n categories of products that aren’t strictly related to each other (i.e. shoes and wine).

My main issue is to figure out a way to deal with category tables/entities that are related to a product table.

The product table will have generic attributes, whilst the attributes that are in the productCatagoryEntity will be specific to the Category.

How can I create an ERD that is flexible enough to deal with this goal?

I’ve considered creating a product_TO_productCategoryEntity table to link the product table and the productCategoryEntity table, when a product is linked to a category the product_TO_productCategoryEntity foreign key attribute related to the Category table will have a non-null value whilst for the categories that aren’t related to the product the FK will be null.

Clearly in the product_TO_productCategoryEntity table I should have listed all the n category tables, this model could lead to hard maintenance.

I’m I going in the right direction?

Please provide any topic, pattern, book or reference that I could eventually study.

enter image description here

@Dan Bracuk's answer, I've included an ERD based on his suggestion:

enter image description here

Was it helpful?

Solution

The design you presented has a serious flaw. You will have to re-design your database every time you add a new category. It would be better to accomplish that by simply adding records. I suggest this design.

Table Product would have a ProductID, name, and not much else.

Table Category would have a CategoryID, name, and not much else.

Table Attribute would have an AttributeID, Type, and value. For example, a type would be colour and the value would be blue.

Then you would have to tables to set up many to many relationships. One would be between Product and Category and the other would be between Product and attribute.

To truly normalize this design, you could have a separate table for AttributeTypes, and have a foreign key reference in the Attribute table.

Edit Starts Here

The schema above would result in the attribute table have records like this:

1|colour|blue
2|colour|red
3|size|small
4|size|medium

That is not normalized because of the repetitive strings colour, and size. To normalize this, you would have a AttributeType table with fields AttributeTypeId and Type Records would look like this:

1|colour
2|size

Your attribute records would then become this:

1|1|blue
2|1|red
3|1|small
4|1|medium

I would actually do it this way. I just got lazy on the original answwer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top