商品可属于多种层级应该如何设计?
请问老师。
现在我有这样一种需求,一个商品可以属于多个分类,举例如下
一个专门卖化妆品的电商可能将同一件商品 A 按照不同的分类方法分到多个分级下
├─ 雅思兰黛
│ └─ 粉底液
│ └─ 沁水系列
│ └─ 商品 A
└─ 兰蔻...
├─ 日常妆容
│ └─ 日系少女
│ └─ 商品 A
└─ 约会晚宴...
现在的数据库中,商品的分类信息被存储在 products.category_id
中,商品只能属于一个分类。
所以我想要实现上述情况分类,只有在现在的基础上再建一张新表 product_categories
来存储商品与分类的一对多的关系
字段名称 | 描述 | 类型 | 加索引缘由 |
---|---|---|---|
id | 自增长ID | unsigned big int | 主键 |
category_id | 类目ID | unsigned big int | 外键 |
product_id | 商品ID | unsigned big int | 外键 |
public function up(){
Schema::create('product_categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->unsignedBigInteger('product_id');
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
});
}
app/Models/ProductCategory.php
class ProductCategory extends Models{
public $timestamps= false;
protected $hidden = ['id'];
protected $fillable = ['product_id','category_id'];
}
对应的 app/Models/Product.php
class Product extends Model{
...
public function categories(){
return $this->hasManyThrough(
Category::class,
ProductCategory::class,
'product_id',
'id',
'id',
'category_id'
);
}
}
请问老师这样设计是否合理呢?如果不合理,请问应该如何设计得更合理呢?
推荐文章: