简体   繁体   English

数据库设计,类别中的项目,子类别和主题

[英]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 我正在使用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. 因此,正确的方法是在产品和类别之间建立m:n关系。 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. 您将看到category表可以使用category_father_id外键自行处理嵌套类别。

But a note to keep in mind is, after all, it is always about your domain/business logic. 但要记住的一点是,毕竟,它始终与您的域/业务逻辑有关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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