Laravel Eloquent: Best Way to Calculate Total Price

前端 未结 2 1353
闹比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:33

    I realise an answer’s already been accepted, but just thought I’d add my own detailing another approach.

    Personally, I like to put “aggregate” methods like these on custom collection classes. So if I have a Buy model that can have many BuyDetail models, then I would put a getTotal() method on my BuyDetailCollection method like this:

    use Illuminate\Database\Eloquent\Collection as EloquentCollection;
    
    class BuyDetailCollection extends EloquentCollection
    {
        public function getTotal()
        {
            return $this->items->sum(function ($detail) {
                return $detail->price * $detail->quantity;
            });
        }
    }
    

    I can then add this to the BuyDetail model:

    class BuyDetail extends Model
    {
        public function newCollection(array $models = [])
        {
            return new BuyDetailCollection($models);
        }
    }
    

    And use my getTotal() method where ever I need to now:

    $buy = Buy::with('buyDetails')->find($id);
    
    $total = $buy->buyDetails->getTotal();
    

提交回复
热议问题