title:Beego的Tag详解
tags: go,beego
我们在文章 Beego的ORM操作之创建表
中,对user结构图用到了一些Tag标签,现在我们就来详细的说明下。
模型设置
auto
当 Field 类型为 int, int32, int64, uint, uint32, uint64 时,可以设置字段为自增健
type Users struct {
.....
AnyField int `orm:"auto"`
}
当模型定义里没有主键时,符合上述类型且名称中带有ID 的 Field 将被视为自增健,如StuID。
pk
设置为主键,适用于自定义其他类型为主键
type Users struct {
.....
AnyField int `orm:"pk"`
}
因为Tag使用方法都一样,就不一一贴代码了
如果想要多个Tag同时使用 可以这样orm:"pk;atuo"
这样就设置为主键自增长。
- 忽略字段
设置 - 即可忽略 struct 中的字段
null
数据库表默认为 NOT NULL,设置 null 代表不允许为空
index
为单个字段增加索引
unique
为单个字段增加 unique 键,让该属性的内容不同重复
column
为字段设置 db 字段的名称,就是设置列名
Name string `orm:"column(user_name)"`
size
设置字段大小,如需设置vchar类型最大长度为60,则用size(60),
digits / decimals
设置 float32, float64 类型的浮点精度
Money float64 `orm:"digits(12);decimals(4)"`
auto_now / auto_now_add
- auto_now 每次 model 保存时都会对时间自动更新
- auto_now_add 第一次保存时才设置时间
Created time.Time `orm:"auto_now_add;type(datetime)"`
Updated time.Time `orm:"auto_now;type(datetime)"`
注意: 对于批量的 update 此设置是不生效的
type
-设置为 date 时,time.Time 字段的对应 db 类型使用 date
Created time.Time `orm:"auto_now_add;type(date)"`
- 设置为 datetime 时,time.Time 字段的对应 db 类型使用 datetime
Created time.Time `orm:"auto_now_add;type(datetime)"`
default
为字段设置默认值,类型必须符合(目前仅用于级联删除时的默认值)