You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Controller中For循环仅执行一次就中断问题排查

问题根源

  • 你初始化$examQuestions时只创建了查询构造器实例,没有提前将对应考试的所有题目查询为集合,每次循环调用find()都会单独执行一次SQL查询,不仅效率极低,还可能出现查询约束异常。
  • 缺少空值判断逻辑:如果某道查询到的题目没有设置isCorrect=true的正确答案,firstWhere()会返回null,此时访问$correctAnswer->content会触发致命错误,直接终止脚本执行,表现就是循环只跑了一次就中断。
  • for循环依赖数组索引连续,一旦$takenQuestions的索引出现断裂就会出现取值异常。

修复方案

直接替换为以下代码即可:

public function calculateResults(){
    $totalCorrect = 0;
    $takenQuestions = request()->input('taken_questions');
    $givenAnswers = request()->input('answer');
    $exam_id = request()->input('exam_id');
    // 提前一次性查询该考试的所有题目,按题目ID作为集合键,方便后续快速查找
    $examQuestions = examQuestion::where('exam_id',$exam_id)->get()->keyBy('id');

    // 改用foreach遍历,不用关心数组索引问题
    foreach($takenQuestions as $index => $questionId){
        // 从预查的集合中获取题目
        $givenQuestion = $examQuestions->get($questionId);
        if(!$givenQuestion) continue;
        
        $correctAnswer = $givenQuestion->answers->firstWhere('isCorrect',true);
        // 增加正确答案空判断,避免报错
        if(!$correctAnswer) continue;

        if($correctAnswer->content == $givenAnswers[$index]){
            $totalCorrect++;
        }
    }

    dd($totalCorrect);
}

额外校验点

如果修复后仍然存在异常,可以新增两个校验点排查:

  • 遍历前打印$givenAnswers的结构,确认其索引和$takenQuestions的索引完全对应
  • 循环内打印每次的$questionId和比对结果,确认是否存在答案不匹配的情况

内容的提问来源于stack exchange,提问作者ellajhonm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:36:02