I'm trying to get the sum of three different columns using Laravel query builder.
I want to calculate the sum of 3 subjects. for example, Student table contains information and record table have marks details with hasmany
relationship.
public function getrecord()
{
$student = Student::with('Record')->get();
return $this->success($student);
}
This is the output I am getting:
// Query working for sum but not loading the Relationship (object details).
$student = Student::addSelect([
'total_marks' => record::wherecolumn('student_id', 'student.id')
->selectRaw('sum(Math+Eng+Urdu) as total_marks')
])->get();
Geniune question: how do you expect this code to load the relationship?
$student = Student::addSelect([
'total_marks' => Record::whereColumn('student_id', 'student.id')
->selectRaw('SUM(Math + Eng + Urdu) AS total_marks')
])->get();
You are missing the with
to eager load the relationship:
$student = Student::with('Record')
->addSelect([
'total_marks' => record::wherecolumn('student_id', 'student.id')
->selectRaw('sum(Math+Eng+Urdu) as total_marks')
])
->get();