在Laravel中建立三重关系的正确方法是什么。我正在使用Laravel的最新版本。
我需要建立品牌/类别/产品关系。
我的桌子是这样的:
Table brands = id - name - slug
Table categories = id - name - slug
Table brand_category = brand_id (foreign key) - category_id (foreign key)
Table products = id - name - slug - brand_id (foreign key) - category_id (foreign key)
需要正确执行:品牌可以有很多类别,反之亦然。品牌和类别也有许多产品。产品通过外键属于品牌和类别。在他们之间建立联系的最好方法是什么?我在这里发布是因为双重的双重关系听起来很奇怪。 Hasmanythrough看起来不错,但我不介意如何涵盖这种关系。
型号:
Brand.php
class Brand extends Model
{
// Table Name
protected $table = 'brands';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;
/**
* The category that belong to the brand.
*/
public function categories()
{
return $this->belongsToMany('App\Category');
}
/**
* Brand has many products.
*/
public function products()
{
return $this->hasMany('App\Product');
}
}
Category.php
class Category extends Model
{
// Table Name
protected $table = 'categories';
/**
* The brand that belongs to the category.
*/
public function brands()
{
return $this->belongsToMany('App\Brand');
}
/**
* The category has many products.
*/
public function products()
{
return $this->hasMany('App\Product');
}
}
Product.php
class Product extends Model
{
//Table Name
protected $table = 'products';
/**
* The product that belongs to the brand.
*/
public function brands()
{
return $this->belongsTo('App\Brand');
}
/**
* The product that belongs to the category.
*/
public function categories()
{
return $this->belongsTo('App\Category');
}
}