每次访问我的模型Product时,我都需要计算折扣后的价格。有存储价格和折扣的字段,但没有折扣后的最终价格。如何在模型中执行此操作,以便每次访问模型中的记录时都会计算折扣价?
发布于 2020-03-20 16:41:48
您可以在产品模型中添加mutators,它将变成一个虚拟属性,如下所示:
public function getPriceAttribute($value)
{
return $value - $this->discount * $value; // Here just the example, add your logic to calculate the price.
}因此,您可以在每个产品中获取折扣后的价格。
Product::first()->price如果不希望折扣价格覆盖原始价格,可以更改为另一个属性名称,如discounted_price
protected $appends = ['discounted_price'];
public function getDiscountedPriceAttribute()
{
return $this->price - $this->discount * $this->price; // Here just the example, add your logic to calculate the price.
}访问discounted_price:
Product::first()->discounted_pricehttps://stackoverflow.com/questions/60770581
复制相似问题