php - 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.
解决方案
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.
推荐阅读
- python - 使用 CELF 的网络中的影响最大化
- powershell - PowerShell 和 conda 的 vscode 问题
- javascript - 为什么类 JS 执行两次?
- excel - Excel 表单控制按钮,可添加新行,但随表格移动
- javascript - 我应该如何将服务器返回的 aes 密钥存储在浏览器中?
- android - Jetpack compose dialogFragment 等效
- git - Git 拒绝跟踪某些文件(git add -f 不工作)
- apache-flink - 当我们更新工作时,flink 如何处理未使用的键控状态字段
- c - 将已经运行的进程运行到其他正在运行的进程的内存中的可能性
- java - 在 Java 中使用 instanceOf 运算符时出错