From 393d8a3a524598430ddb32bf0d130bc1ab1a9940 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sat, 1 Aug 2015 11:27:01 +0800 Subject: [PATCH] Fix possible duplciated foreign key name --- scope_private.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scope_private.go b/scope_private.go index 4b653dba..fdf14dc7 100644 --- a/scope_private.go +++ b/scope_private.go @@ -558,7 +558,8 @@ func (scope *Scope) addIndex(unique bool, indexName string, column ...string) { func (scope *Scope) addForeignKey(field string, dest string, onDelete string, onUpdate string) { var table = scope.TableName() - var keyName = fmt.Sprintf("%s_%s_foreign", table, field) + var keyName = fmt.Sprintf("%s_%s_%s_foreign", table, field, regexp.MustCompile("[^a-zA-Z]").ReplaceAllString(dest, "_")) + keyName = regexp.MustCompile("_+").ReplaceAllString(keyName, "_") var query = `ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s ON DELETE %s ON UPDATE %s;` scope.Raw(fmt.Sprintf(query, scope.QuotedTableName(), scope.QuoteIfPossible(keyName), scope.QuoteIfPossible(field), scope.QuoteIfPossible(dest), onDelete, onUpdate)).Exec() }