什么是模型

来自官方文档

模型是标准的 struct,由 Go 的基本数据类型、实现了 Scanner 和 Valuer 接口的自定义类型及其指针或别名组成

1
2
3
4
5
6
7
8
9
10
11
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
}

关于模型内的指针类型,简单地说就是有指针应当对应可以为 NULL ,请看这篇


模型有什么用

是 gorm 进行各种操作的基础

一个书写良好的模型会让你对数据库的操作事半功倍


模型定义的关键点

约定

GORM 倾向于约定,而不是配置。默认情况下,GORM 使用 ID 作为主键,使用结构体名的 蛇形复数 作为表名,字段名的 蛇形 作为列名,并使用 CreatedAtUpdatedAt 字段追踪创建、更新时间

image-20221001113052392

使用上面的模型建表,id 自动成为主键

gorm.Model

这是 GORM 预定义的一个模型,方便使用的

1
2
3
4
5
6
7
// gorm.Model 的定义
type Model struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
}

嵌入结构体

以匿名结构体

结构体直接是可以直接嵌入的,先看匿名的情况

1
2
3
4
5
6
type User struct {
gorm.Model // 使用匿名结构体形式
Name string
Email *string
Age uint8
}

其实就等于把 gorm.Model 直接平铺进里面

image-20221001114322411

非匿名结构体

而如果要实现层级结构的话(这里指的是在 go 中),就不能匿名

并且加上嵌套字段的标签

1
2
3
4
5
6
7
8
9
10
11
type Model struct {
UUID uint
Time time.Time
}

type User struct {
Model Model `gorm:"embedded"`
Name string
Email *string
Age uint8
}

而且你会发现这样创出来是没有主键的,下面将介绍标签,并使用标签将 UUID 设为主键

标签

标签是用反引号括起来的,里面可以定义一些属性

常用的标签有

  • column
  • primaryKey
  • unique
  • default
  • precision
  • size
  • not null
  • index
  • comment

还有一些是和权限,关联相关的,后面再讲


示例

1
2
3
4
5
6
7
8
9
10
11
type Model struct {
UUID uint `gorm:"primary_key"`
Time time.Time `gorm:"column:my_time"`
}

type User struct {
Model Model `gorm:"embedded;embeddedPrefix:this_is_a_prefix_"` // 添加两个标签
Name string `gorm:"default:'test'"`
Email *string `gorm:"not null"`
Age uint8 `gorm:"comment:'年龄'"`
}

image-20221001120723039