Add support to remove foreign key constraints (#1686)

This commit is contained in:
Amit Yadav 2018-02-09 19:50:26 +05:30 committed by Jinzhu
parent 38f96c6514
commit 0e1cb6ece9
2 changed files with 18 additions and 0 deletions

View File

@ -611,6 +611,14 @@ func (s *DB) AddForeignKey(field string, dest string, onDelete string, onUpdate
return scope.db return scope.db
} }
// RemoveForeignKey Remove foreign key from the given scope, e.g:
// db.Model(&User{}).RemoveForeignKey("city_id", "cities(id)")
func (s *DB) RemoveForeignKey(field string, dest string) *DB {
scope := s.clone().NewScope(s.Value)
scope.removeForeignKey(field, dest)
return scope.db
}
// Association start `Association Mode` to handler relations things easir in that mode, refer: https://jinzhu.github.io/gorm/associations.html#association-mode // Association start `Association Mode` to handler relations things easir in that mode, refer: https://jinzhu.github.io/gorm/associations.html#association-mode
func (s *DB) Association(column string) *Association { func (s *DB) Association(column string) *Association {
var err error var err error

View File

@ -1175,6 +1175,16 @@ func (scope *Scope) addForeignKey(field string, dest string, onDelete string, on
scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName), scope.quoteIfPossible(field), dest, onDelete, onUpdate)).Exec() scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName), scope.quoteIfPossible(field), dest, onDelete, onUpdate)).Exec()
} }
func (scope *Scope) removeForeignKey(field string, dest string) {
keyName := scope.Dialect().BuildForeignKeyName(scope.TableName(), field, dest)
if !scope.Dialect().HasForeignKey(scope.TableName(), keyName) {
return
}
var query = `ALTER TABLE %s DROP CONSTRAINT %s;`
scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.quoteIfPossible(keyName))).Exec()
}
func (scope *Scope) removeIndex(indexName string) { func (scope *Scope) removeIndex(indexName string) {
scope.Dialect().RemoveIndex(scope.TableName(), indexName) scope.Dialect().RemoveIndex(scope.TableName(), indexName)
} }