How to sum of duration column where my course id or section id is same
Asked
Active
Viewed 1,270 times
2 Answers
0
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

felixbmmm
- 362
- 3
- 13
-
When I try to print this $res then I got an array. How can I print this sum by using dd? – Al Shahriar Mehedi Oct 27 '21 at 05:10
-
Inside that array, it has the property named `total_duration`. That is what you're looking for. – felixbmmm Oct 27 '21 at 06:46
0
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');
});

Aachhyo
- 69
- 1
- 3
-
what is your $yourtablenames and what is $yourtablename. my engine can not find $yourtablenames. – Al Shahriar Mehedi Oct 27 '21 at 05:12
-
that is your database table or model name based on how you get data from database – Aachhyo Oct 27 '21 at 06:46
-
You're not even giving us your table/model's name, so people just use other naming for the variable. It's just an usual variable. @AlShahriarMehedi – felixbmmm Oct 27 '21 at 06:47
-
my model name is (App\Models\Lesson)Lesson and table name is lessons.Now how can I calculate and print this.Please share... – Al Shahriar Mehedi Oct 27 '21 at 07:03