我目前正在使用 Laravel 框架构建分配给电子商务项目的 API。在获得构建数据迁移和模型的帮助时,我对产品类别(中间表)如何像多对多关系(产品 <-> 产品类别 <-> 类别)一样链接产品和类别感到困惑。这些是正在开发的模型:
这是类别类: class Category extends Model
class Category extends Model
{
use HasFactory;
protected $fillable = [
'name',
];
public function products()
{
return $this->belongsToMany(
Product::class,
ProductCategory::class,
);
}
}
及产品型号
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name',
'slug',
'price',
'active',
];
protected $casts = [
'price' => 'float',
'active' => 'boolean',
];
public function categories()
{
return $this->belongsToMany(
Category::class,
ProductCategory::class
);
}
public function orderItems()
{
return $this->hasMany(
OrderItem::class,
);
}
}
由于我对此还很陌生,因此我无法从文档中理解是什么使产品和类别链接起来,也无法理解订单模型应该是什么样子。
我正在使用邮递员发出请求,它们与当前的控制器一起工作。所以我的怀疑实际上是概念上的而不是技术上的。