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

Laravel Eloquent关联学生与成绩表默认值显示问题求助

解决方案

1. 定义模型关联

在Student模型中添加与DiagnosticScore的关联(假设每个学生对应一条诊断成绩记录):

// app/Models/Student.php
public function diagnosticScore()
{
    return $this->hasOne(DiagnosticScore::class, 'student_id');
}

2. 控制器预加载关联数据

查询学生数据时预加载诊断成绩,避免N+1查询问题:

// 控制器对应方法
$students = \App\Models\Student::with('diagnosticScore')->get();

3. 修改视图代码

直接通过关联获取成绩,无成绩时显示默认值0:

<tbody>
    @foreach($students as $student)
    <tr>
        <td>{{ $student->id }}</td>
        <td>{{ $student->stud_name }}</td>
        <!-- 用null安全访问+null合并运算符处理无成绩场景 -->
        <td>{{ $student->diagnosticScore?->score ?? 0 }}</td>
        <td class="text-wrap text-center" style="font-size: 12px;">
            <a href="#" id="p1" onclick="document.getElementById('userInput1').value = {{ $student->id }};" data-bs-toggle="modal" data-bs-target="#DeModal">
                <span class="badge badge-primary">
                    insert
                </span>
            </a>
        </td>
    </tr>
    @endforeach
</tbody>

问题原因说明

  • 原代码遍历所有diagnosticScores,每条成绩记录都会生成一个<td>,匹配显示成绩、不匹配显示0,导致每行的列数等于成绩总条数,表格结构完全混乱。
  • 移除else后,仅匹配的成绩生成<td>,无成绩的学生行会缺失该列,同样破坏表格列的一致性。

通过Eloquent关联直接获取当前学生的成绩,既能保证每行只有一个成绩列,无成绩时显示0,同时优化了查询性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:31:34