【问题标题】:Database Design , Items in Category, Sub Category & Theme数据库设计,类别,子类别和主题中的项目
【发布时间】:2013-12-17 21:25:23
【问题描述】:
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

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

对这个设计有什么建议吗?提前致谢!

这是最佳做法吗?尝试正确开始

【问题讨论】:

  • 您的具体问题是什么?您认为潜在问题在哪里?
  • 这是最佳实践吗,我正在尝试正确开始,是数据库设计的新手

标签: php mysql database database-design


【解决方案1】:

让我向您展示一个想法,恕我直言,我认为使用它比较好: 首先创建分类表:

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));

现在通常您可以拥有属于多个类别的产品。因此,正确的做法是在 Product 和 Category 之间建立 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 外键的嵌套类别。

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

【讨论】:

    猜你喜欢
    • 2015-10-15
    • 2011-07-20
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    相关资源
    最近更新 更多