Amrita Stha
Amrita Stha

Reputation: 3327

sum of columns in another table - laravel

There's a loan table and loan_addition table. How can I sum the added_amt of loan_addition table and show them while returning loan table data? loan_addition table

id   loan_id   added_amt
1       1        100
2       1        200 

controller

$data = Loan::select('*')
->with('loanAddition') // how to sum all the columns of respective loan_id here
->get();
dd($data);

loan model

class Loan extends Model
{
    public function loanAddition() {
        return $this->hasMany(LoanAddition::class);
    }
}

LoanAddition model

class LoanAddition extends Model
{
    public function loan()
    {  return $this->belongsTo(Loan::class);  }
}

Thanks in advance..

Upvotes: 0

Views: 122

Answers (2)

SEYED BABAK ASHRAFI
SEYED BABAK ASHRAFI

Reputation: 4271

You can use withSum() method as stated here

$records = Loan::select('*')->withSum('loanAddition', 'loan_id')->get();

Then get the data like below:

$records->pluck('loanAdditions_sum_loan_ids');

Update: for laravel below 8.12

Loan::select('*')->withCount(['loanAddition as loan_id'=>function($query){
        $query->select(DB::raw("SUM(loan_id) as loan_id"));
    }])->get()

Upvotes: 3

DOLWIN DAVIS
DOLWIN DAVIS

Reputation: 91

$data = Loan::select('*')
->with(['loanAddition',function($query){
      $query->select('sum(added_amt) as sum_added_amt')
 }]) // how to sum all the columns of respective loan_id here
->get();
dd($data);

or you can do is $data->first()->sum('loanAddition.added_amt) where you want sum

Upvotes: 0

Related Questions