【问题标题】:How to define a dynamic attribute for a many to many relationship in Laravel 5?如何在 Laravel 5 中为多对多关系定义动态属性?
【发布时间】:2015-08-16 18:44:24
【问题描述】:

我有一个从Orders 到Products 的多对多关系,如下:

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

【问题讨论】:

    标签: php laravel laravel-5 many-to-many accessor


    【解决方案1】:

    是的,你可以,你正在寻找的是 Pivot 类,它很容易实现,这里有一个 tutorial 给你。

    【讨论】:

      猜你喜欢
      • 2016-10-06
      • 2016-05-26
      • 2016-12-10
      • 1970-01-01
      • 2020-08-15
      • 2021-04-04
      • 2016-06-06
      • 2021-01-17
      • 1970-01-01
      相关资源
      最近更新 更多