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

Laravel数据库查询字段累加结果异常偏高,求修复及40题数据高效获取方案

计算结果异常的修复方案

你得到2222的核心原因有两个:

  • 你的where条件存在类型不匹配问题:user_id字段一般为整数类型,存储的是用户的数字ID,你传入的Auth::user()->name是用户名字符串,字段类型不匹配会导致查询到错误记录,加上字段值为字符串类型时运算逻辑异常,最终出现字符串拼接类的错误结果。
  • 重复查询同一张表的同一行,不仅冗余度高,也容易出现不同查询间的数据不一致问题。

修复后的基础代码如下:

class ViewTeacherResults extends Controller
{
    public static function teacherResults() {
        // 匹配逻辑改为用用户ID匹配user_id字段
        $record = DB::table('checklist_teachers')
            ->where('user_id', Auth::user()->id)
            ->first(['int1', 'int2', 'int3', 'int4', 'int5']);
        
        // 空记录兼容处理
        if (!$record) {
            return 0;
        }
        
        // 强制转换为整数后再做算术运算
        $intellectual = (int)$record->int1 + (int)$record->int2 + (int)$record->int3 + (int)$record->int4 + (int)$record->int5;
        return $intellectual;
    }
}
40道题的高效处理方案

针对柱状图展示和批量数据处理的需求,可按以下方案优化,避免写40次重复查询:

  • 单次查询拉取所有字段:仅执行1次SQL查询就获取全部40个题目的字段值,避免多次查询的数据库IO开销。
  • 批量过滤计算:用集合方法批量处理字段,不需要逐个定义变量,代码示例如下:
public static function getChartData() {
    $record = DB::table('checklist_teachers')
        ->where('user_id', Auth::user()->id)
        ->first();
    // 过滤出所有int开头的题目字段,转换为整数格式
    $chartData = collect((array)$record)
        ->filter(function ($value, $key) {
            // PHP版本低于8.0可以替换为 substr($key, 0, 3) === 'int'
            return str_starts_with($key, 'int');
        })
        ->map(fn($val) => (int)$val)
        ->toArray();
    
    // 返回的数组键为字段名、值为对应题目分数,可直接传给前端渲染柱状图
    return $chartData;
}
  • 如果需要做全局统计(比如所有用户每道题的平均分、总分),直接用SQL聚合函数在数据库层面计算即可,不需要把全量数据拉到PHP层处理:
// 统计所有用户每道题的平均分示例
$avgScores = DB::table('checklist_teachers')
    ->selectRaw('AVG(int1) as int1_avg, AVG(int2) as int2_avg, ..., AVG(int40) as int40_avg')
    ->first();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:45:00