I have been asked to create a small program for assignment based on given instructions. I was given two tables I have to create:
product
table with two fields: id
and name
,
category_of_product
table with two fields: product_id
and name
It is said that product can be in many categories.
I was also given example products:
- Product: Nike Shoes, Category: Sneakers, Category: New
- Product: Converse shoes, Category: Trainers, Category: New
etc.
Every example entry has two categories for purpose of the task and finally I have to make a call to database to get Products that are in a
category, but are not in b
category.
First thing that came to my mind was Many-to-Many relation and it still is in my opinion almost the only choice to use. But since I had to I made it this way with duplicate categories where each category can be assigned to only one product.
Finally I have to give pros and cons of the method they gave me and propose alternatives.
The question is: Are there any actual pros to have database set up like that? I thought maybe its a little faster with small amounts of data to query, but I am not sure if this is a good pro for the cons we are getting.
Advertisement
Answer
I cannot think of any “pros” to not defining a relation as it would exist. If the relation is product has one to many categories
then it is a many-to-many relationship and we’d be foolish to try and implement it any other way. Otherwise we cannot guarantee uniqueness, enforce foreign key relations, or create efficient methods for accessing the data.