Search code examples
laraveleloquentmany-to-many

Laravel 5.5 many to many relationship with an intermediate table


Please help,

I have these relationship in laravel between ITEMS, SUPPLIERS and PURCHASE_ORDERS

As ITEMS and SUPPLIERS has many to many relationship, I created an intermediate table between them, called ITEM_SUPPLIER.

Now I need to make a many to many relationship between PURCHASE_ORDERS and the intermediate table ITEM_SUPPLIER.

How do I make the relationship? Should I create an intermediate table between them, what's the best way to name it?


Solution

  • Add a model for pivot table ItemSupplier whth extra column id which extends Pivot

    use Illuminate\Database\Eloquent\Relations\Pivot;
    
    class ItemSupplier extends Pivot
    {
    
        public function purchaseOrder()
        {
           return $this->belongsToMany(PURCHASE_ORDERS::class, item_supplier_purchase_order);
        }
    
    }
    

    As you see you need to create a new item_supplier_purchase_order pivot table and add the relationships

    class PURCHASE_ORDERS extends Model
    {
    
        public function purchaseOrder()
        {
           return $this->belongsToMany(ItemSupplier::class, item_supplier_purchase_order);
        }
    
    }