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

如何基于result字段设置is_complete?PHP代码问题求助

解决思路:用PHP后端实现才是正确选择

嘿,我来帮你搞定这个问题!首先明确:这种考试成绩判定和状态更新绝对要在PHP后端处理,前端JS做这个太不安全了——用户很容易篡改前端数据绕过你的判断,导致状态更新出错。你的场景是提交表单后计算成绩,后端处理完全可行,而且是最优解。

你的现有代码问题出在哪?

你Model里的passed()方法逻辑完全走偏了:

  • 新建了多个无关的ExamResult实例,根本没操作当前提交后生成的那条考试记录
  • 用ExamResult::where('result', '>=', 2)->get()获取了一堆记录,然后去判断集合是否≥2,这逻辑完全不对,你要判断的是当前这条记录的result值
  • 最后也没有保存修改后的is_complete字段,等于白忙活

修正后的代码方案

1. 重写Model的passed()方法

让这个方法直接操作当前的ExamResult实例,逻辑清晰直接:

public function answers()
{
    return $this->hasMany('App\ExamResultsAnswers');
}

public function passed()
{
    // 检查当前记录的result是否≥2,是的话更新is_complete并保存
    if ($this->result >= 2) {
        $this->is_complete = 1;
        $this->save();
    }
}

2. 保持Controller的调用逻辑(只需改一个小拼写)

你Controller里的逻辑大部分是对的,只需要把answers数组里的corect改成correct(拼写错误),然后调用$exam_result->passed()就可以了,因为此时$exam_result已经有了计算好的result值:

public function exam($course_id, Request $request)
{
    $course = Course::where('id', $course_id)->firstOrFail();
    $answers = [];
    $exam_score = 0;
    foreach ($request->get('question') as $question_id => $answer_id) {
        $question = ExamQuestion::find($question_id);
        $correct_answer = ExamOption::where('exam_question_id', $question_id)
            ->where('id', $answer_id)
            ->where('is_correct', 1)->count() > 0;
        $answers[] = [
            'exam_question_id' => $question_id,
            'exam_option_id' => $answer_id,
            'correct' => $correct_answer // 这里修正拼写错误
        ];
        if ($correct_answer) {
            $exam_score += $question->score;
        }
    }
    $exam_result = ExamResult::create([
        'exam_id' => $course->exam->id,
        'employee_id' => \Auth::id(),
        'result' => $exam_score,
    ]);
    $exam_result->answers()->createMany($answers);
    // 调用passed方法,自动判断并更新is_complete
    $exam_result->passed();
    return redirect()->route('learn.show', [$course, $request])->with('message', 'Test score: ' . $exam_score);
}

额外优化建议

如果想更简洁,甚至可以不用单独写passed()方法,直接在创建$exam_result的时候就设置is_complete:

$exam_result = ExamResult::create([
    'exam_id' => $course->exam->id,
    'employee_id' => \Auth::id(),
    'result' => $exam_score,
    'is_complete' => $exam_score >= 2 ? 1 : 0 // 直接在这里设置状态
]);

这样连passed()方法都可以省掉,逻辑更直接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:30:07