Database Design , Items in Category, Sub Category & Theme

拟墨画扇 提交于 2019-12-24 12:13:07

问题


CREATE TABLE Product (ProductID int, Description nvarchar(100))

CREATE TABLE CategoryID (CategoryID int, Description nvarchar(100),ProductID int)
CREATE TABLE SubCategoryID (SubCategoryID int, CategoryID int, Description nvarchar(100),ProductID int)

CREATE TABLE ThemeID (ThemeID int, Description nvarchar(100),ProductID int)

I'm using Laravel ORM

Product hasMany-> Category
Product hasMany-> SubCategory
Product hasMany-> Theme

Category BelongsTo->Product
SubCategory BelongsTo->Category
Theme BelongsTo -> Product

Each item has got a theme and belongs to multiple category, Sub Category is Optional.

Any advice on this design? Thanks in advance!

Is this best practice? Trying to Start right


回答1:


Let show you an idea which IMHO I think it is good to be used: first create the category table:

CREATE TABLE `category` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `category_father_id` int(11) DEFAULT '0',
  `is_active` tinyint(1) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`),
  KEY `category_father_id` (`category_father_id`),
  CONSTRAINT `constraint_name` FOREIGN KEY (`category_father_id`) REFERENCES `category` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;

then for your product table you can keep it as it is:

CREATE TABLE Product (ProductID int, Description nvarchar(100));

Now Usually you can have a Product which belongs to several categories. Hence, the correct way to do it is to have m:n relation between Product and Category. and it can be done by adding:

create table product_category(
ProductId int(11) not null,
CategoryId int(11) not null,
unique (ProductId,CategoryId),
foreign key (ProductId) references Product (ProductID) on update cascade on delete cascade,
foreign key (CategoryId) references category (id) on update cascade on delete cascade
)engine=innodb;

and you can keep the theme as it is.

you will see that category table can handles the nesting categories using category_father_id foreign key on it self.

But a note to keep in mind is, after all, it is always about your domain/business logic.



来源:https://stackoverflow.com/questions/20323748/database-design-items-in-category-sub-category-theme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!