如何创建正确的数据库结构以避免重复数据
How to create the correct database structure to avoid duplicate data
我在项目中使用类别。现在我的类别数据库结构是这样的:
id
title
description
slug
parent_id
问题:
我目前有两个产品类别。第一类是“销售”产品,第二类是“购买”产品。在“销售”类别中,卖家列出他们的待售产品。而在“购买”类别中,买家放置了一些要购买的产品。在这种情况下,两个类别将具有相同的子类别。在我的 table 结构中,我正在为两个类别复制子类别,如下所示:
促销
- 手袋
- 鞋子
- 连衣裙
买入
- 手袋
- 鞋子
- 连衣裙
数据库
id | title | description | slug | parent_id
-------------------------------------------
1 | Sale | null | sale | null
2 | Bags | null | bags | 1
3 | Shoes | null | shoes| 1
4 | Dress | null | dress| 1
5 | Buy | null | buy | null
6 | Bags | null | bags | 2
7 | Shoes | null | shoes| 2
8 | Dress | null | dress| 2
-------------------------------------------
如何创建正确的 table 结构来避免出现重复的子类别?
我现在只有 tables products
和 categories
。
嗯,首先,您不一定需要有两个单独的类别来进行销售/购买。
因为如果你这样做,你可以拥有完全相同子类别的唯一方法是镜像它们(在你的代码中各处创建、编辑、删除 2 次)
另一种解决方案是一个枢轴table,这样您的子类别就可以有多个父类别(多对多关系)
但如果你想坚持简单的一对多关系,我建议制作一个通用父类别,并在你的菜单中使用它两次,一次用于销售,一次用于购买。
编辑:
如果您想采用多对多方法,您的迁移将如下所示:
Schema::create('category_relations', function (Blueprint $table) {
$table->unsignedBigInteger('parent_id');
$table->unsignedBigInteger('child_id');
});
和你的模特:
Class Category extends Model{
public function parents(){
return $this->belongsToMany(Category::class,'category_relations','child_id','parent_id');
}
public function children(){
return $this->belongsToMany(Category::class,'category_relations','parent_id','child_id');
}
}
我在项目中使用类别。现在我的类别数据库结构是这样的:
id
title
description
slug
parent_id
问题:
我目前有两个产品类别。第一类是“销售”产品,第二类是“购买”产品。在“销售”类别中,卖家列出他们的待售产品。而在“购买”类别中,买家放置了一些要购买的产品。在这种情况下,两个类别将具有相同的子类别。在我的 table 结构中,我正在为两个类别复制子类别,如下所示:
促销
- 手袋
- 鞋子
- 连衣裙
买入
- 手袋
- 鞋子
- 连衣裙
数据库
id | title | description | slug | parent_id
-------------------------------------------
1 | Sale | null | sale | null
2 | Bags | null | bags | 1
3 | Shoes | null | shoes| 1
4 | Dress | null | dress| 1
5 | Buy | null | buy | null
6 | Bags | null | bags | 2
7 | Shoes | null | shoes| 2
8 | Dress | null | dress| 2
-------------------------------------------
如何创建正确的 table 结构来避免出现重复的子类别?
我现在只有 tables products
和 categories
。
嗯,首先,您不一定需要有两个单独的类别来进行销售/购买。
因为如果你这样做,你可以拥有完全相同子类别的唯一方法是镜像它们(在你的代码中各处创建、编辑、删除 2 次)
另一种解决方案是一个枢轴table,这样您的子类别就可以有多个父类别(多对多关系)
但如果你想坚持简单的一对多关系,我建议制作一个通用父类别,并在你的菜单中使用它两次,一次用于销售,一次用于购买。
编辑: 如果您想采用多对多方法,您的迁移将如下所示:
Schema::create('category_relations', function (Blueprint $table) {
$table->unsignedBigInteger('parent_id');
$table->unsignedBigInteger('child_id');
});
和你的模特:
Class Category extends Model{
public function parents(){
return $this->belongsToMany(Category::class,'category_relations','child_id','parent_id');
}
public function children(){
return $this->belongsToMany(Category::class,'category_relations','parent_id','child_id');
}
}