gorm中字段的tag都有哪些
时间: 2024-03-23 22:40:55 浏览: 132
在 GORM 中,可以使用不同的标记(tag)来为模型中的字段指定不同的选项。下面是一些常用的 GORM 标记:
primary_key
:指定该字段为主键。not null
:指定该字段不能为空。unique
:指定该字段的值必须是唯一的。default
:指定该字段的默认值。size
:指定该字段的大小(例如:size:255
)。precision
:指定该字段的精度(例如:precision:10
)。scale
:指定该字段的比例(例如:scale:2
)。auto_increment
:指定该字段为自增长。index
:指定该字段需要创建索引。type
:指定该字段的数据类型(例如:type:varchar(100)
)。comment
:指定该字段的注释。unique_index
:指定该字段需要创建唯一性索引。
例如,以下是一个包含多个标记的 GORM 模型的示例:
type User struct {
ID uint `gorm:"primary_key"`
Name string `gorm:"not null;size:50;unique_index"`
Email string `gorm:"not null;unique_index"`
Password string `gorm:"not null"`
Age int `gorm:"not null;default:18"`
CreatedAt time.Time
UpdatedAt time.Time
}
在上面的示例中,User
模型使用了多个标记,包括 primary_key
、not null
、size
、unique_index
、default
和 unique
。这些标记用于指定每个字段的不同选项,例如 Name
字段必须不能为空、必须具有最大大小为 50 个字符,并且需要创建唯一性索引。
阅读全文
相关推荐


















