From a8b3e8d3e2e6e7f540b0c8eaec3d18479a7435dd Mon Sep 17 00:00:00 2001 From: sendyHalim Date: Sat, 7 Feb 2015 18:04:10 +0700 Subject: [PATCH 1/2] Add Scope.addForeignKey() --- main.go | 11 +++++++++++ scope_private.go | 14 ++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/main.go b/main.go index 11929ce1..9d016641 100644 --- a/main.go +++ b/main.go @@ -400,6 +400,17 @@ func (s *DB) AddIndex(indexName string, column ...string) *DB { return s } +/* +Add foreign key to the given scope + +Example: + db.Model(&User{}).AddForeignKey("city_id", "cities(id)", "RESTRICT", "RESTRICT") +*/ +func (s *DB) AddForeignKey(field string, dest string, onDelete string, onUpdate string) *DB { + s.clone().NewScope(s.Value).addForeignKey(field, dest, onDelete, onUpdate) + return s +} + func (s *DB) AddUniqueIndex(indexName string, column ...string) *DB { s.clone().NewScope(s.Value).addIndex(true, indexName, column...) return s diff --git a/scope_private.go b/scope_private.go index 79e00ee2..7dd02d38 100644 --- a/scope_private.go +++ b/scope_private.go @@ -630,6 +630,20 @@ func (scope *Scope) addIndex(unique bool, indexName string, column ...string) { scope.Raw(fmt.Sprintf("%s %v ON %v(%v);", sqlCreate, indexName, scope.QuotedTableName(), strings.Join(columns, ", "))).Exec() } +func (scope *Scope) addForeignKey(field string, dest string, onDelete string, onUpdate string) { + var table string = scope.TableName() + var keyName string = fmt.Sprintf("%s_%s_foreign", table, field) + var query string = ` + ALTER TABLE %s + ADD CONSTRAINT %s + FOREIGN KEY (%s) + REFERENCES %s + ON DELETE %s + ON UPDATE %s; + ` + scope.Raw(fmt.Sprintf(query, table, keyName, field, dest, onDelete, onUpdate)).Exec() +} + func (scope *Scope) removeIndex(indexName string) { scope.Dialect().RemoveIndex(scope, indexName) } From d861d8737e0960731158733c0feee8aafd935b42 Mon Sep 17 00:00:00 2001 From: Sendy Halim Date: Sat, 7 Feb 2015 18:08:25 +0700 Subject: [PATCH 2/2] Update README.md --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index f8349ac5..9b787e70 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,13 @@ db.AutoMigrate(&User{}, &Product{}, &Order{}) // Add index db.Model(&User{}).AddIndex("idx_user_name", "name") +// Add foreign key +// 1st param : foreignkey field +// 2nd param : destination table(id) +// 3rd param : ONDELETE +// 4th param : ONUPDATE +db.Model(&User{}).AddForeignKey("user_id", "destination_table(id)", "CASCADE", "RESTRICT") + // Multiple column index db.Model(&User{}).AddIndex("idx_user_name_age", "name", "age")