Golang中Gorm返回零值问题的CamelCase解析

Golang中Gorm返回零值问题的CamelCase解析 你好,我在执行一个查询时,它返回了所有值,但 userId 总是零值。然而,如果我将驼峰命名改为 userid,它就能正常工作。以下是我的模型和输出。

注意:

我不想使用 *gorm.Model

我的模型

 package students
 // import "gorm.io/gorm"
 type Students struct {
     // *gorm.Model
     Id     int    `json:"id"`
     UserId int    `json:"userId"`
     Name   string `json:"name"`
     Age    int    `json:"age"`
 }

输出。

[
   {
     "id": 1,
     "userId": 0,
     "name": "Alejandro Castillo",
     "age": 26
   },
   {
     "id": 2,
     "userId": 0,
     "name": "Doom Metal",
     "age": 44
   }
 ]

更多关于Golang中Gorm返回零值问题的CamelCase解析的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

尝试添加 gorm 标签

gorm:"column:{column name in db}"

更多关于Golang中Gorm返回零值问题的CamelCase解析的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


你好,谢谢,这样是可行的。

package students
// import "gorm.io/gorm"

type Students struct {
    // *gorm.Model
    Id     int    `json:"id"`
    UserId int    `gorm:"column:userId"`
    Name   string `json:"name"`
    Age    int    `json:"age"`
}

在Golang的Gorm中,当数据库列名使用蛇形命名(如user_id)而结构体字段使用驼峰命名(如UserId)时,需要明确指定列名映射。Gorm默认使用蛇形命名转换,但UserId转换后是user_id,而你的数据库列名可能是userid

以下是解决方案:

  1. 明确指定列名标签
type Students struct {
    Id     int    `json:"id" gorm:"column:id"`
    UserId int    `json:"userId" gorm:"column:userid"`
    Name   string `json:"name" gorm:"column:name"`
    Age    int    `json:"age" gorm:"column:age"`
}
  1. 使用Gorm的命名策略配置(如果数据库列名是user_id):
import "gorm.io/gorm"

db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
    NamingStrategy: schema.NamingStrategy{
        TablePrefix: "",
        SingularTable: true,
        NameReplacer: nil,
        NoLowerCase: false,
    },
})
  1. 检查实际数据库列名
-- 查看表结构
DESCRIBE students;
-- 或
SHOW COLUMNS FROM students;
  1. 完整示例代码
package main

import (
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
    "gorm.io/gorm/logger"
)

type Students struct {
    Id     int    `json:"id" gorm:"column:id"`
    UserId int    `json:"userId" gorm:"column:user_id"` // 或 userid
    Name   string `json:"name" gorm:"column:name"`
    Age    int    `json:"age" gorm:"column:age"`
}

func main() {
    db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
        Logger: logger.Default.LogMode(logger.Info),
    })
    if err != nil {
        panic(err)
    }

    var students []Students
    result := db.Find(&students)
    if result.Error != nil {
        panic(result.Error)
    }
}

关键点:通过gorm:"column:xxx"标签明确指定数据库列名,这是最可靠的解决方案。

回到顶部