models下的go文件
// 默认的表名规则,使用驼峰转蛇形:
// AuthUser -> auth_user
// Auth_User -> auth__user
// DB_AuthUser -> d_b__auth_user
// 除了开头的大写字母以外,遇到大写会增加 _,原名称中的下划线保留
type Store struct {
Id int
Title string
Created time.Time `orm:"index"`
Views int `orm:"index"`
TopicTime time.Time `orm:"index"`
TopicCount int `orm:"column(topicCount)"` // 自定义列名
TopicLastUserId int `orm:"default(1)"`
Created time.Time `orm:"auto_now_add;type(datetime)"`
Updated time.Time `orm:"auto_now;type(datetime)"`
// auto_now 每次 model 保存时都会对时间自动更新
// auto_now_add 第一次保存时才设置时间
}
// 默认表名为store 如果要自定义表名,需要下面代码
func (u *Store) TableName() string {
return "auth_store"
}
type Customer struct {
Id int
Uid int
Title string
Content string `orm:"size(5000)"`
Attachment string
Created time.Time `orm:"index"`
Updated time.Time `orm:"index"`
Views int `orm:"index"`
Author string
ReplyTime time.Time `orm:"index"`
ReplyCount int
ReplyLastUserId int
}
// 在使用 ORM 的地方调用 models.RegisterDB()
func RegisterDB() {
//注册 model
orm.RegisterModel(new(Store), new(Customer))
//注册驱动
orm.RegisterDriver("mysql", orm.DRMySQL)
//注册默认数据库
orm.RegisterDataBase("default", "mysql", "username:password@tcp(127.0.0.1:3306)/godb?charset=utf8")
}
自动建表,在main.go文件的main函数下面
// 自动建表
models.RegisterDB() // models.RegisterDB() 只在第一次运行服务的时候注册一次
orm.RunSyncdb("default", false, true)