Merge pull request #360 from sendyhalim/scope-add-foreignkey

Add Scope.addForeignKey()
This commit is contained in:
Jinzhu 2015-02-11 19:35:57 +08:00
commit 6dc33d6d94
3 changed files with 32 additions and 0 deletions

View File

@ -147,6 +147,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")

11
main.go
View File

@ -397,6 +397,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

View File

@ -633,6 +633,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)
}