Gorm: 声明模型(1)
建议点击 查看原文 查看最新内容。
原文链接:
https://typonotes.com/posts/2025/03/17/gorm-model-declaration/
1. 数组字段
https://gorm.io/zh_CN/docs/models.html
如果表中有 slice 字段, 则需要使用 type
指定类型。
1
2
3
4
5
6
| package dao
type DemoTable struct {
Users []string `gorm:"type:text[]"` // This is a slice of strings
IDs []int `gorm:"type:int[]"` // This is a slice of integers
}
|
2. 索引
https://gorm.io/zh_CN/docs/indexes.html
2.1 唯一作引
唯一索引有两种形式,
uniqueIndex
index:[name],unique
: 自定义索引名字
1
2
3
4
5
| type User struct {
Name string `gorm:"index"` // 索引
Name4 string `gorm:"uniqueIndex"` // 唯一索引
Name2 string `gorm:"index:idx_name,unique"` // 命名+唯一索引
}
|
2.2. 复合索引
多个字段使用相同的索引名字, 则创建 复合索引
1
2
3
4
5
| // create composite index `idx_member` with columns `name`, `number`
type User struct {
Name string `gorm:"index:idx_member"`
Number string `gorm:"index:idx_member"`
}
|
3. 外键
https://gorm.io/zh_CN/docs/constraints.html
通过 constraint
标签的 OnDelete
, OnUpdate
选项设置外键约束,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| type User struct {
gorm.Model
CompanyID int
Company Company `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
CreditCard CreditCard `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}
type CreditCard struct {
gorm.Model
Number string
UserID uint
}
type Company struct {
ID int
Name string
}
|
3.1. 禁用外键约束
在初始化数据库的时候, 使用参数 DisableForeignKeyConstraintWhenMigrating
禁用外键约束。
1
2
3
| db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
})
|