天天看点

gorm查询结果无法填充到结构体中,以及gorm中文版、英文版和源码地址

今天使用gorm开发时,明明定义了结构体,但gorm没有把数据填充到结构体对象中,这是为什么呢?如代码所示:

// 定义结构体
type ComplaintCount struct {
    Pending                    int64  
    Processed                  int64  
    BetweenOneDayAndThreeDay   int64  
    BetweenThreeDayAndSevenDay int64 
    BeyondSevenDay             int64  
}

//方法执行
func CountComplaint(c context.Context, params map[string]interface{}) (ret *ComplaintCount, err error) {

    db := dao.db.Table("complaint")
    db = db.Select(`count( IF ( status = 1, 1, NULL ) ) as Pending, 
                    count( IF ( status = 2, 1, NULL ) ) as Processed,
                    count(IF(TIMESTAMPDIFF(day,createdAt,NOW())>=0 AND TIMESTAMPDIFF(day,createdAt,NOW())<2 AND status = 1,1,NULL)) as BetweenOneDayAndThreeDay,
                    count(IF(TIMESTAMPDIFF(day,createdAt,NOW())>=2 AND TIMESTAMPDIFF(day,createdAt,NOW())<6 AND status = 1 ,1,NULL)) BetweenThreeDayAndSevenDay,
                    count(IF(TIMESTAMPDIFF(day,createdAt,NOW())>=6 AND status = 1 ,1,NULL)) AS BeyondSevenDay `)
    var result ComplaintCount
    
    err = db.Find(&result).Error
    if err != nil {
        return
    }
    ret = &result
    return
}

           

但是,原生的SQL语句是有数据的,这是什么呢?

原来gorm在定义模型时,需要说明列名,也就是说,该列名至少有两个作用

  1. 将go结构体的属性对应相应表的字段名
  2. 将go结构体的属性对应查询语句的别名

上面的查询语句满足第二个条件,因而,结构体需要修改为这样的:

type ComplaintCount struct {
    Pending                    int64 `gorm:"column:Pending"`
    Processed                  int64 `gorm:"column:Processed"`
    BetweenOneDayAndThreeDay   int64 `gorm:"column:BetweenOneDayAndThreeDay"`
    BetweenThreeDayAndSevenDay int64 `gorm:"column:BetweenThreeDayAndSevenDay"`
    BeyondSevenDay             int64 `gorm:"column:BeyondSevenDay"`
}
           

如此修改,便有数据了

备注,gorm模型定义传送门:

  1. 中文版
  2. 英文版
  3. githup地址