首页 > 解决方案 > Running eloquent in loop and display list in blade based on result from another eloquent query

问题描述

I have a query that gets a list of students and Iam using a foreach loop to iterate and get the student_id of each student.

Inside the foreach loop I have another query that calculates the student marks. When calculating the student marks, i need the student_id which is from the first query

Logic

$students = DB::table('grades_students')
  ->join('users', 'grades_students.student_id', '=', 'users.id')
  ->join('grades', 'grades_students.grade_id', '=', 'grades.id')
  ->where('grades.stream_id', $request->stream_name)
  ->get()->pluck('student_id');


  foreach ($students as $student ) {

    $student_average=DB::select(DB::raw("select student_id,  round((SUM(t.mark))/'5') average_mark from (
        select marks.student_id,  ROUND(AVG(mark)) as mark  from marks
            INNER JOIN teaching_loads ON teaching_loads.id=marks.teaching_load_id
            INNER JOIN subjects ON subjects.id=teaching_loads.subject_id
        where marks.student_id = '$student' AND marks.assessement_id=1  
        GROUP BY subject_id
      )t "));

}
return view('analytics.view-test', compact('student_average'));   



Now the problem is that in blade only one student appears and yet I need to show a list of all students who are in students query.

标签: phpmysqllaraveleloquentlaravel-blade

解决方案


You're overwriting $student_average each loop, so only the contents of the last loop are stored in $student_average. You need to use an array instead.

$student_averages = [];
foreach ($students as $student) {
    $student_averages[] = DB::select(...your query);
}
return view('analytics.view-test', compact('student_averages'));

Then you will have all the student averages available and can loop through them in your view.


推荐阅读