0

Here is the relation

  1. transaction hasMany Carts
  2. Cart belongsTo product
  3. product->price

here is the Model class

//# TransactionModel
public function getCarts(){
    return $this->hasMany(CartModel::class, 'transaction_id','id');
}
//# CartModel
public function getProduct(){
    return $this->belongsTo(ProductModel::class,'product_id','id');
}

what i want to achieve is to get total price of current transactions(many)

what i do now is still iterate per transation and sum the price in $total

 Class TransactionModel{
 public static function getTotalPrice($transactions){
    $total = 0;
    foreach($transactions as $transaction){
            $total += $transaction->getCarts->sum('getProduct.price');
    }
    return $total;
 }

how to this in eloquent code thanks

david valentino
  • 920
  • 11
  • 18

2 Answers2

0

I Think this should work :

Class TransactionModel{

    public function getTotalPrice(){

        return $this->getCarts()->withCount([
            'getProduct' => function($q){ 
                return $q->select(DB::raw("SUM(price) as price_sum")); 
            }
        ])->get()->sum('getProduct_count');
    }

}
Mihir Bhende
  • 8,677
  • 1
  • 30
  • 37
0

i finally found a better way with collection reduce instead of foreach

 $totalPrice = $transactions->reduce(function($carry, $current){
                    return $carry + $current->getCarts->sum('getProduct.price');
               },0);
david valentino
  • 920
  • 11
  • 18