func runMigrations(appCtx AppContext) { appCtx.Logger.Info("Running database…
- User
func runMigrations(appCtx *AppContext) { appCtx.Logger.Info("Running database migrations...") err := appCtx.DB.AutoMigrate(&models.User{}, &models.NotionPage{}, &models.Permission{}, &models.RolePermission{}) if err != nil { appCtx.Logger.Fatal("Database migration failed", zap.Error(err)) } appCtx.Logger.Info("Database migrations completed") }
func runMigrations(appCtx *AppContext) { appCtx.Logger.Info("Running database migrations...") err := appCtx.DB.AutoMigrate(&models.User{}, &models.NotionPage{}, &models.Permission{}, &models.RolePermission{}) if err != nil { appCtx.Logger.Fatal("Database migration failed", zap.Error(err)) } appCtx.Logger.Info("Database migrations completed") }
每次新加表或修改表结构都要对应修改这种 migrate 的参数吗,有没有什么一劳永逸的,类似 Spring 自动扫描的做法
func runMigrations(appCtx *AppContext) { appCtx.Logger.Info("Running database migrations...") err := appCtx.DB.AutoMigrate(&models.User{}, &models.NotionPage{}, &models.Permission{}, &models.RolePermission{}) if err != nil { appCtx.Logger.Fatal("Database migration failed", zap.Error(err)) } appCtx.Logger.Info("Database migrations completed") }
- Assistant
你当前的做法是把要迁移的所有模型手动一个个列出来,的确每次改模型都需要去
AutoMigrate()调用里增加或修改对应的模型,比较繁琐。在 Go 里没有像 Spring 那样完整的反射扫描框架,但可以用几种方法减少手工维护的麻烦:
方案一:注册模型切片,统一管理
定义一个模型切片,把所有模型都放进去,之后迁移的时候遍历:
var allModels = []interface{}{ &models.User{}, &models.NotionPage{}, &models.Permission{}, &models.RolePermission{}, } func runMigrations(appCtx *AppContext) { appCtx.Logger.Info("Running database migrations...") for _, model := range allModels { err := appCtx.DB.AutoMigrate(model) if err != nil { appCtx.Logger.Fatal("Database migration failed", zap.Error(err)) } } appCtx.Logger.Info("Database migrations completed") }以后新增模型只要添加到
allModels中即可。
方案二:利用 函数自动注册模型