簡體   English   中英

如何在自定義透視類laravel5中添加mutators

[英]How to add mutators in custom pivot class laravel5

訂單和產品之間有many to many關系。 數據透視表order_product還有其他列: pricequantity 我有自定義透視類:

class OrderProduct extends Pivot
{
    protected $attributes = ['price', 'quantity'];

    public function getPriceAttribute($value)
    {
        return number_format($value, 2);
    }

    public function setPriceAttribute($value)
    {
        $price = $value - ($value * 0.1);
        $this->attributes['price'] = $price;
    }    
}

class Product extends Model
{
    public function orders()
    {
        return $this->belongsToMany(Order::class, 'order_product')->using('App\Models\OrderProduct')->withPivot('price','quantity');
    }
}

Accessor有效,但mutator沒有。
如何使mutator setPriceAttributesync()attach()

$valuesetPriceAttribute是正確的,但修改不適用於DB?

在相關模型中實現mutators和accessors。

class Product extends Model
{




  public function getPriceAttribute($value)
   {
    return number_format($value, 2);
   }

  public function setPriceAttribute($value)
  {
    $price = $value - ($value * 0.1);
    $this->attributes['price'] = $price;
  } 
  public function orders()
   {
     return $this->belongsToMany(Order::class, 'order_product')->using('App\Models\OrderProduct')->withPivot('price','quantity');
   }
}

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM