【发布时间】:2021-01-22 08:14:24
【问题描述】:
我正在尝试为产品和类别制作关系表。
这是我的产品模型
protected $table = 'products';
protected $fillable = ['sku', 'slug', 'type'];
public function category()
{
return $this->belongsTo('Modules\Product\Entities\Categories', 'categories_products', 'category_id', 'id');
}
这是我的类别模型:
protected $table = 'categories';
protected $fillable = ['parent_id', 'name'];
public function parent()
{
return $this->hasOne(self);
}
public function products()
{
return $this->hasMany('Modules\Product\Entities\Products', 'categories_products', 'product_id', 'id');
}
每次我尝试获取具有以下类别的产品时:
public function getProducts()
{
return Products::with('category')->get();
}
它返回的类别为空。我的关系表称为 categories_products,它有 2 个整数 product_id 和 category_id。
【问题讨论】:
-
只需将表名
categories_products重命名为category_product单数项