首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在模型中计算价格,每次访问laravel中的模型而不保存在数据库中

在模型中计算价格,每次访问laravel中的模型而不保存在数据库中
EN

Stack Overflow用户
提问于 2020-03-20 16:12:58
回答 1查看 376关注 0票数 0

每次访问我的模型Product时,我都需要计算折扣后的价格。有存储价格和折扣的字段,但没有折扣后的最终价格。如何在模型中执行此操作,以便每次访问模型中的记录时都会计算折扣价?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-20 16:41:48

您可以在产品模型中添加mutators,它将变成一个虚拟属性,如下所示:

代码语言:javascript
复制
    public function getPriceAttribute($value)
    {
        return $value - $this->discount * $value; // Here just the example, add your logic to calculate the price.
    }

因此,您可以在每个产品中获取折扣后的价格。

代码语言:javascript
复制
Product::first()->price

如果不希望折扣价格覆盖原始价格,可以更改为另一个属性名称,如discounted_price

代码语言:javascript
复制
    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:

代码语言:javascript
复制
Product::first()->discounted_price
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60770581

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档