Files
go_blog/models/init.go

61 lines
1.1 KiB
Go
Raw Normal View History

2024-01-10 16:05:15 +08:00
/*
@Time : 2020/6/28 21:46
@Author : xuyiqing
@File : init.py
*/
package models
import (
"fmt"
"go_blog/conf"
"go_blog/pkg/util"
"time"
2024-07-04 19:15:44 +08:00
"gorm.io/driver/mysql"
2024-01-23 18:29:13 +08:00
"gorm.io/gorm"
2024-07-04 19:15:44 +08:00
"gorm.io/gorm/schema"
2024-01-10 16:05:15 +08:00
)
var DB *gorm.DB
func SetUp(isOrmDebug bool) {
conUri := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local",
conf.DataBase.User,
conf.DataBase.Password,
conf.DataBase.Host,
conf.DataBase.Port,
2024-07-04 19:15:44 +08:00
conf.DataBase.DBName,
2024-01-10 16:05:15 +08:00
conf.DataBase.Charset)
2024-07-04 19:15:44 +08:00
db, err := gorm.Open(mysql.Open(conUri), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
TablePrefix: conf.DataBase.Prefix,
},
})
2024-01-10 16:05:15 +08:00
if err != nil {
panic(err)
}
DB = db
DB.AutoMigrate(&Account{})
2024-01-23 18:29:13 +08:00
DB.AutoMigrate(&Content{})
2024-07-04 19:15:44 +08:00
DB.AutoMigrate(&Contents{})
2024-01-10 16:05:15 +08:00
}
type BaseModel struct {
ID uint64 `gorm:"primary_key'" json:"id"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
DeletedAt *time.Time `sql:"index" json:"-"`
}
// 生成全局唯一ID
2024-07-04 19:15:44 +08:00
func (m *BaseModel) BeforeCreate(scope *gorm.DB) error {
2024-01-10 16:05:15 +08:00
if m.ID == 0 {
m.ID = util.GenSonyFlakeId()
}
return nil
}