How to sum of duration column where my course id or section id is same
2 Answers
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');
});
4 Comments
Al Shahriar Mehedi
what is your $yourtablenames and what is $yourtablename. my engine can not find $yourtablenames.
Aachhyo
that is your database table or model name based on how you get data from database
felixbmmm
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
Al Shahriar Mehedi
my model name is (App\Models\Lesson)Lesson and table name is lessons.Now how can I calculate and print this.Please share...
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
2 Comments
Al Shahriar Mehedi
When I try to print this $res then I got an array. How can I print this sum by using dd?
felixbmmm
Inside that array, it has the property named
total_duration. That is what you're looking for.