dongyan5706 2016-12-29 11:07
浏览 94
已采纳

Laravel价格计算

I've tried to calculate the total sum of an order with help of this: Laravel Eloquent: Best Way to Calculate Total Price

I want the calculation to be done in the model, so I can use it in multiple controllers.

My code looks like this:

class Order extends Model
{
    public function customer()
    {
        return $this->belongsTo('App\Customer');
    }

    public function orderItems()
    {
        return $this->hasMany('App\OrderItem');
    }

    public function total()
    {
        return $this->orderItems->sum(function($orderItem)
            {
                return $orderItem->net_price;
            });
    }
}

So I think I have done everything exactly like in the example, but I'm getting following error:

ErrorException in Model.php line 2696: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

Any help will be highly appreciated.
Thanks.

  • 写回答

4条回答 默认 最新

  • dsg7513 2016-12-29 12:36
    关注

    Joha, I would be very careful using the sum function on a collection when you are working with decimal values. This will not be relevant if you are using integer values.

    You may find that the sum function will sometimes miscalculate the sum, and leave you with quirky numbers like 59.999999999998184. This is because decimal operations aren't very stable in computers, so you must loop around each item and use bcmath instead to avoid this. Even if you're not experiencing it now, as the app grows, this would become a problem.

    Here would be a more secure & accurate example:

    class Order extends Model{
    
        public function customer()
        {
            return $this->belongsTo('App\Customer');
        }
    
        public function orderItems()
        {
            return $this->hasMany('App\OrderItem');
        }
    
        public function getTotalAttribute() {
            $totalPrice = 0;
    
            foreach ($this->orderItems as $orderItem) {
                $totalPrice = bcadd($totalPrice, $orderItem->net_price, 2);
            }
    
            return $totalPrice;
        }
    }
    

    I would also refactor the function into an attribute, as shown in the code example. This allows you to access $order->total as if it was an attribute on the model.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题