1、前言
在 GORM
中,模型定义是采用标准的 struct
,例如:
type User struct {
ID uint
Name string
Email *string
Age uint8
Birthday *time.Time
MemberNumber sql.NullString
ActivatedAt sql.NullTime
CreatedAt time.Time
UpdatedAt time.Time
}
2、约定
GORM
默认使用 ID
作为主键,使用结构体名的 蛇形复数
形式作为表名,结构体字段名的 蛇形
作为列名。
3、声明模型配置细节
3.1 如何配置模型
通过在声明结构体时,为每个结构体字段的标签指定 gorm
标签,在该标签中进行具体配置。例如:
type User struct {
Account string `gorm:"type:char(20);not null;default:'';comment:用户账号"`
}
3.2 嵌入结构体
GORM
定义了一个 gorm.Model
结构体,其包括字段 ID
、CreatedAt
、UpdatedAt
、DeletedAt
type Model struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
}
// ID 作为主键
// CreatedAt 记录创建时间
// UpdatedAt 记录更新时间
// DeletedAt 删除时间(软删除标记)
您可以将它嵌入到您的结构体中,以包含这几个字段
type User struct {
gorm.Model
Name string
}
// 等效于
type User struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
Name string
}
3.3 创建和更新时间设置精度
可以设置的精度有:纳秒、毫秒、秒、Time,例如:
type User struct {
CreatedAt time.Time // 在创建时,如果该字段值为零值,则使用当前时间填充
UpdatedAt int // 在创建时该字段值为零值或者在更新时,使用当前时间戳秒数填充
Updated int64 `gorm:"autoUpdateTime:nano"` // 使用时间戳纳秒数填充更新时间
Updated int64 `gorm:"autoUpdateTime:milli"` // 使用时间戳毫秒数填充更新时间
Created int64 `gorm:"autoCreateTime"` // 使用时间戳秒数填充创建时间
}
四、常用字段标签
4.1 column
指定 db 列名
4.2 type
列数据类型,推荐使用兼容性好的通用类型,例如:所有数据库都支持 bool、int、uint、float、string、time、bytes 并且可以和其他标签一起使用,例如:not null、size, autoIncrement… 像 varbinary(8) 这样指定数据库数据类型也是支持的。在使用指定数据库数据类型时,它需要是完整的数据库数据类型,如:MEDIUMINT UNSIGNED not NULL AUTO_INCREMENT
4.3 serializer
指定将数据序列化或反序列化到数据库中的序列化器, 例如: serializer:json/gob/unixtime
4.4 size
定义列数据类型的大小或长度,例如 size: 256
4.5 primaryKey
将列定义为主键
4.6 unique
将列定义为唯一键
4.7 default
定义列的默认值
4.8 precision
指定列的精度
4.9 scale
指定列大小
4.10 not null
指定列为 NOT NULL
4.11 autoIncrement
指定列为自动增长
4.12 autoIncrementIncrement
自动步长,控制连续记录之间的间隔
4.13 embedded
嵌套字段
4.14 embeddedPrefix
嵌入字段的列名前缀
4.15 autoCreateTime
创建时追踪当前时间,对于 int
字段,它会追踪时间戳秒数,您可以使用 nano/milli
来追踪纳秒、毫秒时间戳,例如:autoCreateTime:nano
4.16 autoUpdateTime
创建/更新时追踪当前时间,对于 int
字段,它会追踪时间戳秒数,您可以使用 nano/milli
来追踪纳秒、毫秒时间戳,例如:autoUpdateTime:milli
4.17 index
根据参数创建索引,多个字段使用相同的名称则创建复合索引,查看 索引 获取详情
4.18 uniqueIndex
与 index
相同,但创建的是唯一索引
4.19 check
创建检查约束,例如 check:age > 13
,查看 约束 获取详情
4.20 <-
设置字段写入的权限, <-:create
只创建、<-:update
只更新、<-:false
无写入权限、<-
创建和更新权限
4.21 ->
设置字段写入的权限, <-:create
只创建、<-:update
只更新、<-:false
无写入权限、<-
创建和更新权限
4.22 -
忽略该字段,-
表示无读写,-:migration
表示无迁移权限,-:all
表示无读写迁移权限
4.23 comment
迁移时为字段添加注释