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
📝 发现内容有误?点击此处直接编辑