You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

39 lines
1.1 KiB

// GORM 自动迁移, 创建表
// 1.读取 etc/usercenter.yaml 文件, 获取配置,连接数据库
// 2.遍历 orm 包下的所有文件, 获取所有表名,自动迁移
// 1.读取 etc/usercenter.yaml 文件, 获取配置,连接数据库
package orm
import (
"backend/usercenter/api/internal/config"
"backend/usercenter/orm"
"flag"
"fmt"
"github.com/zeromicro/go-zero/core/conf"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var configFile = flag.String("yaml", "etc/usercenter.yaml", "the config file")
func AutoMigrate() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", c.MySQL.User, c.MySQL.Password, c.MySQL.Host, c.MySQL.Port, c.MySQL.DBName)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
// 自动迁移 User 表
fmt.Println("迁移User表")
if err := db.AutoMigrate(&orm.User{}); err != nil {
panic(err)
}
fmt.Println("迁移User表完成")
// 迁移完成,打印信息
fmt.Println("全部迁移完成")
}