Laravel Eloquent: Best Way to Calculate Total Price

前端 未结 2 1355
闹比i
闹比i 2021-02-12 19:53

Im building a simple buy and sell application with Laravel 5.1. Each Buy Model has many BuyDetail which stores bought item quantity and buy_price. I have implement the relations

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-12 20:34

    This can be done in (at least) 2 ways.

    Using pure Eloquent model logic:

    class Buy extends Model
    {
      public function getTotalPrice() {
        return $this->buyDetails->sum(function($buyDetail) {
          return $buyDetail->quantity * $buyDetail->price;
        });
      }
    }
    

    The only issue here is that it needs to fetch all buy details from the database but this is something you need to fetch anyway to display details in the view.

    If you wanted to avoid fetching the relation from the database you could build the query manually:

    class Buy extends Model
    {
      public function getTotalPrice() {
        return $this->buyDetails()->sum(DB::raw('quantity * price'));
      }
    }
    

提交回复
热议问题