0

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..

2 Answers 2

3

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()
Sign up to request clarification or add additional context in comments.

2 Comments

Its throwing an error - Call to undefined method Illuminate\Database\Eloquent\Builder::withSum()
@AmritaStha this needs Laravel 8.12 and above
0
$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

2 Comments

Column not found: 1054 Unknown column 'sum(added_amt)'
Instead I've used the following as well but it return empty - $q->select(DB::raw('sum(added_amt) as sum_added_amt'));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.