Laravel / Eloquent三重模型多对多关系

时间:2018-03-06 04:34:25

标签: php laravel-5 eloquent many-to-many pivot-table

我正在尝试用Eloquent(Laravel 5.5)写作:

我的表格结构如下

  1. 产品
  2. 颜色
  3. 尺寸
  4. colour_product - 数据透视表
  5. 我有一系列产品和颜色(多对多)。对于每种产品 - 颜色对有多种尺寸。我需要像'colour_product_sizes'这样的东西。请使用Laravel Eloquent建议一种方法。

    Product.php(产品型号)

        <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Product extends Model
    {
       use \Dimsav\Translatable\Translatable;
       public $translatedAttributes = ['name','short_description'];
    
    
       public function colours()
       {
        return $this->belongsToMany(Colour::class,'colour_product')->withTimestamps();
       }
    
       public function sizes()
       {
        return $this->belongsToMany(Size::class);
       } 
    
    
    }
    
    ?>
    

    Colour.php(颜色模型)

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Colour extends Model
    {
       use \Dimsav\Translatable\Translatable;
    
       public $translatedAttributes = ['name'];
       protected $fillable = ['code'];
    
       public function products()
       {
        return $this->belongsToMany(Product::class);
       }
    }
    ?>
    

    Size.php(尺寸模型)

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Size extends Model
    {
    
       use \Dimsav\Translatable\Translatable;
    
       public $translatedAttributes = ['name','short_name','extra'];    
       protected $fillable = ['code'];
    
       public function products()
       {
        return $this->belongsToMany(Product::class);
       }
    
    }
    ?>
    

    colour_product表架构

    1   id  int(10) UNSIGNED    
    2   product_id  int(10) UNSIGNED    
    3   colour_id   int(10) UNSIGNED    
    4   created_at  datetime    
    5   updated_at  datetime 
    

0 个答案:

没有答案