Skip to content

Commit 0e1cb6e

Browse files
ayadavjinzhu
authored andcommitted
Add support to remove foreign key constraints (go-gorm#1686)
1 parent 38f96c6 commit 0e1cb6e

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

Diff for: main.go

+8
Original file line numberDiff line numberDiff line change
@@ -611,6 +611,14 @@ func (s *DB) AddForeignKey(field string, dest string, onDelete string, onUpdate
611611
return scope.db
612612
}
613613

614+
// RemoveForeignKey Remove foreign key from the given scope, e.g:
615+
// db.Model(&User{}).RemoveForeignKey("city_id", "cities(id)")
616+
func (s *DB) RemoveForeignKey(field string, dest string) *DB {
617+
scope := s.clone().NewScope(s.Value)
618+
scope.removeForeignKey(field, dest)
619+
return scope.db
620+
}
621+
614622
// Association start `Association Mode` to handler relations things easir in that mode, refer: https://jinzhu.github.io/gorm/associations.html#association-mode
615623
func (s *DB) Association(column string) *Association {
616624
var err error

Diff for: scope.go

+10
Original file line numberDiff line numberDiff line change
@@ -1175,6 +1175,16 @@ func (scope *Scope) addForeignKey(field string, dest string, onDelete string, on
11751175
scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName), scope.quoteIfPossible(field), dest, onDelete, onUpdate)).Exec()
11761176
}
11771177

1178+
func (scope *Scope) removeForeignKey(field string, dest string) {
1179+
keyName := scope.Dialect().BuildForeignKeyName(scope.TableName(), field, dest)
1180+
1181+
if !scope.Dialect().HasForeignKey(scope.TableName(), keyName) {
1182+
return
1183+
}
1184+
var query = `ALTER TABLE %s DROP CONSTRAINT %s;`
1185+
scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName))).Exec()
1186+
}
1187+
11781188
func (scope *Scope) removeIndex(indexName string) {
11791189
scope.Dialect().RemoveIndex(scope.TableName(), indexName)
11801190
}

0 commit comments

Comments
 (0)