laravelrelationshiphas-many

How can we load the Relationship in Laravel with sum of different column?


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:
Image shows the student_id exist in the record table

// 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();

Output:
Getting sum but not details of object see the image


Solution

  • 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();