1

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.

1
  • You're overwriting $student_average in the loop. You need to create an array to use it in a loop Commented Apr 13, 2021 at 12:36

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The code is working, thank you for letting me know the logic of why only one user is returned
1

You should do this

// Create an array to store the value
$student_average = [];

foreach ($students as $student) {
    // Push result to array
    $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 "));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.