在 GORM 中,可以使用标签(tag)来定义和应用约束,这些约束将在模型与数据库表之间进行映射。下面是 GORM 中常用的约束及其用法的详细解释:
primaryKey
标签将字段标记为主键。gotype User struct {
ID uint `gorm:"primaryKey"`
Name string
Age int
}
autoIncrement
标签将字段标记为自动增长。gotype User struct {
ID uint `gorm:"primaryKey;autoIncrement"`
Name string
Age int
}
unique
标签将字段标记为唯一约束。gotype User struct {
ID uint `gorm:"primaryKey"`
Name string `gorm:"unique"`
Age int
}
not null
标签将字段标记为非空约束。gotype User struct {
ID uint `gorm:"primaryKey"`
Name string `gorm:"not null"`
Age int
}
default
标签指定字段的默认值。gotype User struct {
ID uint `gorm:"primaryKey"`
Name string `gorm:"default:'John'"`
Age int `gorm:"default:18"`
}
foreignKey
标签定义外键关系。外键约束需要在相关联的模型之间建立关联,并使用 references
标签指定外键关联的字段。gotype User struct {
ID uint `gorm:"primaryKey"`
RoleID uint
Role Role `gorm:"foreignKey:RoleID"`
}
type Role struct {
ID uint `gorm:"primaryKey"`
Name string
}
index
标签在字段上创建索引。gotype User struct {
ID uint `gorm:"primaryKey"`
Name string `gorm:"index"`
Age int
}
这些约束标签可以组合使用,以适应更复杂的需求。在定义完模型结构体后,可以使用 AutoMigrate()
函数将约束应用于数据库表。
请注意,约束的具体语法和用法可能会因数据库类型而有所不同,因此在使用特定数据库时,建议
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!