繁体   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)

我正在使用Laravel ORM

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

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

每个项目都有一个主题,属于多个类别,子类别是可选的。

有关此设计的任何建议吗? 提前致谢!

这是最佳做法吗? 试着开始吧

让我们告诉你一个想法,我认为擅长使用它:首先创建类别表:

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;

那么对于你的产品表,你可以保持原样:

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

现在通常您可以拥有属于多个类别的产品。 因此,正确的方法是在产品和类别之间建立m:n关系。 它可以通过添加:

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;

你可以保持主题不变。

您将看到category表可以使用category_father_id外键自行处理嵌套类别。

但要记住的一点是,毕竟,它始终与您的域/业务逻辑有关。

暂无
暂无

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

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