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

Gorm无法根据结构体创建完整表仅生成ID字段,如何解决?

Gorm仅生成ID字段问题解决方法

问题根源在于结构体字段的可见性规则:Gorm仅能识别首字母大写的导出字段,你定义的symbols和symbolsCount是小写开头的非导出字段,Go语言不允许外部包(这里的Gorm)访问这类字段,所以Gorm无法读取它们的结构信息,自然不会生成对应的表列。

修改后的代码如下:

package main

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

type Word struct {
    ID           uint
    Symbols      string // 首字母大写转为导出字段
    SymbolsCount int    // 首字母大写转为导出字段
}

func main() {
    db, err := gorm.Open(sqlite.Open("words.db"), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    db.AutoMigrate(&Word{})

    db.Create(&Word{
        Symbols:      "test",
        SymbolsCount: len("test"),
    })
}

执行后,words表会生成id、symbols、symbols_count三个字段(Gorm默认将驼峰命名转为下划线格式的列名)。

如果想保留结构体字段的小写命名风格,可通过Gorm标签指定列名,但前提还是要将字段改为导出(首字母大写):

type Word struct {
    ID           uint
    Symbols      string `gorm:"column:symbols"`
    SymbolsCount int    `gorm:"column:symbols_count"`
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 20:20:02