全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-21 6 分钟 ✍️ juanwangdev

gorm tag 使用

GORM 通过结构体标签(tag)配置字段与数据库列的映射关系,实现灵活的表结构定义。

什么是 gorm tag

gorm tag 是 Go 结构体字段的元数据注解,用于指定字段在数据库中的列名、类型、约束等属性。

常用标签

column - 指定列名

Go
type User struct {
    ID       uint   `gorm:"column:user_id"`
    UserName string `gorm:"column:username"`
}

type - 指定数据库类型

Go
type Product struct {
    ID    uint    `gorm:"primaryKey"`
    Name  string  `gorm:"type:varchar(256)"`
    Price float64 `gorm:"type:decimal(10,2)"`
    Info  string  `gorm:"type:text"`
}

primaryKey - 主键

Go
type Order struct {
    OrderNo string `gorm:"primaryKey"`
    UserID  uint
    Amount  float64
}

autoIncrement - 自增

Go
type User struct {
    ID uint `gorm:"primaryKey;autoIncrement"`
}

组合使用示例

Go
type User struct {
    ID        uint      `gorm:"primaryKey;autoIncrement;column:id"`
    Name      string    `gorm:"type:varchar(100);not null;column:real_name"`
    Email     string    `gorm:"type:varchar(255);uniqueIndex"`
    Age       int       `gorm:"column:age"`
    CreatedAt time.Time `gorm:"column:created_at"`
}

常用标签速查

标签用途示例
column指定列名gorm:"column:user_name"
type指定数据库类型gorm:"type:varchar(255)"
primaryKey设为主键gorm:"primaryKey"
autoIncrement设为自增gorm:"autoIncrement"
not null非空约束gorm:"not null"
uniqueIndex唯一索引gorm:"uniqueIndex"

注意事项

  • 多个标签用分号 ; 分隔
  • type 标签值需符合数据库类型规范
  • primaryKey 和 autoIncrement 通常配合使用
  • column 标签用于覆盖默认的蛇形命名规则

要点总结

标签核心作用
column自定义列名
type指定字段类型
primaryKey定义主键
autoIncrement启用自增
组合使用多标签用分号分隔

存放路径:D:\git2\jwdev\articles\GORM\入门\模型标签与字段配置\gorm tag 使用.md

📝 发现内容有误?点击此处直接编辑

← 上一篇 GORM 查询记录基础
下一篇 → 命名约定与映射规则
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库