Hi all.
I recently started a webshop for a vintage store. It has been some time since I last had to do a webshop and I can’t figure out what would be the best approach. My first thought was to use 3 tables:
products, categories and product_categories
I think the first two tables speak for themselves.
Products:
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
`description` longtext COLLATE utf8mb4_unicode_ci,
`price` decimal(10,2) NOT NULL,
`in_stock` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
and categories:
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
I wanted to use the third table, product_categories, as a link table between products and categories. This would allow a product to be linked to multiple categories
CREATE TABLE IF NOT EXISTS `product_categories` (
`category_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
PRIMARY KEY (`category_id`,`product_id`),
KEY `IDX_D2B6356B88C5F785` (`category_id`),
KEY `IDX_D2B6356B7294869C` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Only with this setup I ran a little too fast. The owner told me that she didn’t consider it necessary to place a product under multiple categories. However, she would like to see a sub category added to the structure as well. This second wish wasn’t difficult to solve by simply adding an extra field, parent_id to the table categories. Only I can’t figure out how I link the various products to the table categories now that there is also a sub category in the game.
I would really appreciate it if someone could nudge me in the right direction or tell me that it might be better to use a completely different structure to solve this.
Thank you in advance