简体   繁体   中英

Database Design , Items in Category, Sub Category & Theme

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM