[英]How to add mutators in custom pivot class laravel5
訂單和產品之間有many to many
關系。 數據透視表order_product
還有其他列: price
, quantity
。 我有自定義透視類:
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 setPriceAttribute
與sync()
, attach()
?
$value
在setPriceAttribute
是正確的,但修改不適用於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.