diff --git a/gorm.go b/gorm.go index 6027b4bb..47a209ab 100644 --- a/gorm.go +++ b/gorm.go @@ -30,6 +30,8 @@ type Config struct { PrepareStmt bool // DisableAutomaticPing DisableAutomaticPing bool + // DisableForeignKeyConstraintWhenMigrating + DisableForeignKeyConstraintWhenMigrating bool // ClauseBuilders clause builder ClauseBuilders map[string]clause.ClauseBuilder diff --git a/migrator/migrator.go b/migrator/migrator.go index 64e02ac7..a239c926 100644 --- a/migrator/migrator.go +++ b/migrator/migrator.go @@ -97,11 +97,13 @@ func (m Migrator) AutoMigrate(values ...interface{}) error { } for _, rel := range stmt.Schema.Relationships.Relations { - if constraint := rel.ParseConstraint(); constraint != nil { - if constraint.Schema == stmt.Schema { - if !tx.Migrator().HasConstraint(value, constraint.Name) { - if err := tx.Migrator().CreateConstraint(value, constraint.Name); err != nil { - return err + if !m.DB.Config.DisableForeignKeyConstraintWhenMigrating { + if constraint := rel.ParseConstraint(); constraint != nil { + if constraint.Schema == stmt.Schema { + if !tx.Migrator().HasConstraint(value, constraint.Name) { + if err := tx.Migrator().CreateConstraint(value, constraint.Name); err != nil { + return err + } } } } @@ -179,11 +181,13 @@ func (m Migrator) CreateTable(values ...interface{}) error { } for _, rel := range stmt.Schema.Relationships.Relations { - if constraint := rel.ParseConstraint(); constraint != nil { - if constraint.Schema == stmt.Schema { - sql, vars := buildConstraint(constraint) - createTableSQL += sql + "," - values = append(values, vars...) + if !m.DB.DisableForeignKeyConstraintWhenMigrating { + if constraint := rel.ParseConstraint(); constraint != nil { + if constraint.Schema == stmt.Schema { + sql, vars := buildConstraint(constraint) + createTableSQL += sql + "," + values = append(values, vars...) + } } }