Home > Back-end >  How to sum of column in laravel with relationship
How to sum of column in laravel with relationship

Time:10-27

enter image description here

How to sum of duration column where my course id or section id is same

CodePudding user response:

You have to use hasMany relation on this table with course and section table. For hasMany relation see this docs. Here

Then, you can use foreach to generate the sum.

$summation = $yourtablenames->sum(function ($yourtablename) {
    return $yourtablename->your_relation_name->sum('duration');
});

CodePudding user response:

Try this code:

$res = Model::groupBy('course_id', 'section_id')
   ->selectRaw('sum(duration) as total_duration, course_id, section_id') // do the sum query here
   ->pluck('total_duration','course_id', 'section_id'); // get the related query column here

Source answer

  • Related