标签说明
除了上述的BelongsTo、HasOne、HasMany和ManyToMany标签外,Gorm还提供了其他标签,用于进一步细化模型之间的关系。以下是一些常用标签的说明:
primaryKey: 指定主键字段。uniqueIndex: 指定唯一索引字段。index: 指定普通索引字段。default: 指定默认值。size: 指定字段大小。not null: 指定字段非空。autoCreateTime: 自动创建记录的时间戳。autoUpdateTime: 自动更新记录的时间戳。
下面是一些标签示例:
代码语言:javascript复制type User struct {
gorm.Model
Name string `gorm:"uniqueIndex"`
Age int `gorm:"index"`
Gender string `gorm:"size:255;not null"`
CreatedAt time.Time `gorm:"autoCreateTime"`
UpdatedAt time.Time `gorm:"autoUpdateTime"`
DeletedAt *time.Time `gorm:"index"`
}在上述代码中,我们为User模型中的各个字段添加了不同的标签,以实现不同的功能。例如,我们使用了uniqueIndex标签来指定Name字段为唯一索引字段,使用了index标签来指定Age字段为普通索引字段,使用了size标签来指定Gender字段的大小,使用了not null标签来指定Gender字段非空,使用了autoCreateTime和autoUpdateTime标签来自动创建和更新记录的时间戳,使用了index标签来指定DeletedAt字段为索引字段。


