【问题标题】:Select sum with joining table on gorm golang在gorm golang上选择带有连接表的总和
【发布时间】:2021-09-04 08:06:59
【问题描述】:

假设我有 3 个这样的模型

type Violation struct{
  ID uint `gorm:"primaryKey"`
  ViolationName string
  ViolationPoint int
}

type Student struct{
  ID uint `gorm:"primaryKey"`
  StudentName string
}

type ViolationRecord struct{
  ID uint `gorm:"primaryKey"`
  ViolationID int
  V Violation `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;foreignKey:ViolationID;references:ID"`
  StudentID int
  S Student `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;foreignKey:StudentID;references:ID"`
  RecordDate time.Time
}

CRUD 系统一切正常,但新的请求是显示违规记录/学生的总数并总结违规点。

我试过了

type ViolationSummary struct {
    count int
    sum   int
}

func(s *Server) ShowSummary(id int){
  var vs ViolationSummary
  s.DB.Table("violation_records").
            Select("count(violation_records.id) as count, sum(violations.violation_point) 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)
}

但是这个函数总是显示0值

【问题讨论】:

    标签: go-gorm


    【解决方案1】:

    我已经用这段代码解决了我的问题,我希望它可以帮助。

    func(s *Server) ShowSummary(id int){
     vr:= []models.ViolationRecord{}
     var total int64 = 0
     var point int64 = 0
     err:= s.DB.Where("student_id = ?",id).Preload(clause.Associations).Find(&vr).Error
     if err != nil {
     fmt.println("Error on load data")
     }
     for _, element := range vr {
            total += 1
            point += int64(element.V.ViolationPoint)
    
        }
    fmt.println(total)
    fmt.println(point)
    }
    

    【讨论】:

    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    相关资源
    最近更新 更多