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

Laravel中如何展示考生用户的答题总数与正确数

实现考生答题统计表格的解决方案

我来帮你一步步搞定这个需求,分后端数据查询和前端视图渲染两部分来实现:

第一步:在控制器中查询统计数据

首先你需要在对应的控制器方法里,筛选出同时是考生的用户,并统计他们的总答题数和正确答题数。利用Eloquent的关联和聚合查询可以轻松实现:

// 示例控制器方法
public function examineeStats()
{
    // 筛选出拥有考生记录的用户,并统计答题数据
    $examineeUsers = User::has('examinee') // 只保留关联了Examinee的用户
        ->withCount([
            // 统计总答题数:如果用户可能重复提交同一题,加distinct去重;否则去掉distinct即可
            'submittedAnswers as total_answered' => function ($query) {
                $query->distinct('exam_quiz_id');
            }
        ])
        ->withCount([
            // 统计正确答题数:关联ExamQuizAnswer表判断是否为正确答案
            'submittedAnswers as correct_answered' => function ($query) {
                $query->join('exam_quiz_answers', 'submitted_answers.exam_quiz_answer_id', '=', 'exam_quiz_answers.id')
                      ->where('exam_quiz_answers.is_correct_ans', true);
            }
        ])
        ->get();

    // 将数据传递到视图
    return view('your-target-view', compact('examineeUsers'));
}

代码说明:

  • has('examinee'):确保只查询已经关联了考生记录的用户,精准匹配你“同时为考生的用户”的要求。
  • withCount:Laravel提供的快捷聚合方法,通过别名total_answered和correct_answered区分两种统计结果,方便视图直接调用。
  • 总答题数去重逻辑:如果允许用户重复提交同一道题,distinct('exam_quiz_id')可以避免重复计数;如果不需要去重,直接移除这个方法即可。

第二步:在视图中渲染表格

拿到后端传递的$examineeUsers数据后,就可以在视图里循环渲染表格了:

<table>
    <tr>
        <th>Name</th>
        <th>Answered</th>
        <th>Correct</th>
    </tr>
    @foreach($examineeUsers as $user)
    <tr>
        <td>{{ $user->name }}</td> {{-- 默认Laravel用户表包含name字段,直接调用即可 --}}
        <td>{{ $user->total_answered }}</td>
        <td>{{ $user->correct_answered }}</td>
    </tr>
    @endforeach
</table>

补充说明:

如果你的姓名字段不在users表(比如存在于examinees表),只需把$user->name替换为关联字段即可:

<td>{{ $user->examinee->name }}</td>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:49:13