gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:13:06 24 4
gpt4 key购买 nike

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 外键处理嵌套类别。

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

关于php - 数据库设计,类别,子类别和主题中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20323748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com