beego模型类 - Go语言中文社区

beego模型类


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)
版权声明:本文来源简书,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.jianshu.com/p/3b5b38613fc3
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-01-12 11:58:43
  • 阅读 ( 1001 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢