0
votes

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

2
It should be something like $transaction->getCarts->product->sum('price') - Iftikhar uddin
@Iftikharuddin thats what i did, only get current transation. what we want to achieve is total price of many transaction(S) - david valentino
What version of Laravel are you using? Also, please may you show the code for all 3 models. - Rwd
Can you update your question with Model relationships? what dos getcarts do? - Mihir Bhende
@RossWilson updated. - david valentino

2 Answers

0
votes

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');
    }

}
0
votes

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);