2015-08-16 26 views
0

我已經從Order s至Product秒的多對多的關係,如下所示:如何在Laravel 5中爲多對多關係定義動態屬性?

class Order extends Model { 
    ... 
    public function products() 
    { 
     return $this->belongsToMany('App\Product') 
        ->withPivot('unit_price', 'quantity'); 
    } 
} 

我可以使用$order->pivot->unit_price$order->pivot->quantity訪問關係的屬性。

但是有沒有一種方法可以爲這種關係創建訪問器?
例如,$order->pivot->subTotal將返回unit_price * quantity

回答

1

是的,你可以,你正在尋找的是Pivot類,它很容易實現,這裏是你的tutorial