Go GORM 获取数据库最大 ID 为 0 的问题及解决方案

问题描述:

使用 Go GORM 库查询数据库最大 ID 时,结果始终为 0。代码示例如下:

type MaxIdStruct struct {
    MaxId int64 `json:'maxId' `
}

func main() {
    db := // ... 数据库连接
    maxIdVal := MaxIdStruct{}
    result := db.Raw('select max(id) as maxId from wemeet_agency_customer').Scan(&maxIdVal)
    // ... 处理结果
}

问题原因:

出现该问题的原因可能是没有给 MaxIdStruct 结构体的 MaxId 字段设置 GORM 标签,导致无法正确解析查询结果。

解决方案:

在 MaxId 字段上添加 GORM 标签 gorm:'column:maxId',将查询结果中的 maxId 字段映射到结构体的 MaxId 字段上。

type MaxIdStruct struct {
    MaxId int64 `json:'maxId' gorm:'column:maxId'`
}

解释:

  • gorm:'column:maxId' 表示将查询结果中的 maxId 列映射到结构体的 MaxId 字段。

代码示例:

type MaxIdStruct struct {
    MaxId int64 `json:'maxId' gorm:'column:maxId'`
}

func main() {
    db := // ... 数据库连接
    maxIdVal := MaxIdStruct{}
    result := db.Raw('select max(id) as maxId from wemeet_agency_customer').Scan(&maxIdVal)
    // ... 处理结果
}

注意:

  • GORM 标签必须使用单引号 ' 包裹。
  • column 标签用于指定数据库列名与结构体字段名的对应关系。
  • 如果数据库表字段名与结构体字段名一致,可以省略 column 标签。

原文地址: https://www.cveoy.top/t/topic/oIK1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录