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

Go GORM关联查询学生违规记录数与总扣分值始终返回0求助

问题原因

  • 核心问题:ViolationSummary 结构体的count和sum字段首字母为小写,属于Go语言的未导出私有字段,GORM的Scan方法无法通过反射给私有字段赋值,因此两个字段一直保持int类型的默认值0。
  • 可选优化点:当指定学生没有违规记录时,SQL的sum()聚合函数会返回NULL,直接映射到int类型也会得到0,无法区分「真的没有违规总分为0」和「查询异常返回0」的情况。

修复方案

步骤1:修改统计结果结构体,将字段改为导出(首字母大写),可搭配gorm标签明确映射字段别名

type ViolationSummary struct {
    Count int `gorm:"column:count"`
    Sum   int `gorm:"column:sum"`
}

步骤2:优化SQL查询,对sum结果做IFNULL处理,避免NULL值问题

func(s *Server) ShowSummary(id int){
  var vs ViolationSummary
  s.DB.Table("violation_records").
            Select("count(violation_records.id) as count, IFNULL(sum(violations.violation_point), 0) as sum").
            Joins("left join violations on violation_records.violation_id=violations.id").
            Where("student_id = ?", id).
            Scan(&vs)
  fmt.Println(vs.Count)
  fmt.Println(vs.Sum)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:51:03