Laravel Triple Relationship - PullRequest
       50

Laravel Triple Relationship

0 голосов
/ 11 января 2019

Как правильно сделать тройные отношения в 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');
    }
}
...