Create join table when run AutoMigrate

This commit is contained in:
Jinzhu 2014-07-30 14:20:38 +08:00
parent 14590a65dc
commit 371e6af99e
1 changed files with 18 additions and 13 deletions

View File

@ -426,12 +426,7 @@ func (scope *Scope) related(value interface{}, foreignKeys ...string) *Scope {
return scope return scope
} }
func (scope *Scope) createTable() *Scope { func (scope *Scope) createJoinTable(field *Field) {
var sqls []string
for _, field := range scope.Fields() {
if !field.IsIgnored && len(field.SqlTag) > 0 {
sqls = append(sqls, scope.Quote(field.DBName)+" "+field.SqlTag)
}
if field.JoinTable != nil && field.JoinTable.joinTable != "" { if field.JoinTable != nil && field.JoinTable.joinTable != "" {
if !scope.Dialect().HasTable(scope, field.JoinTable.joinTable) { if !scope.Dialect().HasTable(scope, field.JoinTable.joinTable) {
newScope := scope.db.NewScope("") newScope := scope.db.NewScope("")
@ -445,6 +440,15 @@ func (scope *Scope) createTable() *Scope {
scope.Err(newScope.db.Error) scope.Err(newScope.db.Error)
} }
} }
}
func (scope *Scope) createTable() *Scope {
var sqls []string
for _, field := range scope.Fields() {
if !field.IsIgnored && len(field.SqlTag) > 0 {
sqls = append(sqls, scope.Quote(field.DBName)+" "+field.SqlTag)
}
scope.createJoinTable(field)
} }
scope.Raw(fmt.Sprintf("CREATE TABLE %v (%v)", scope.QuotedTableName(), strings.Join(sqls, ","))).Exec() scope.Raw(fmt.Sprintf("CREATE TABLE %v (%v)", scope.QuotedTableName(), strings.Join(sqls, ","))).Exec()
return scope return scope
@ -494,6 +498,7 @@ func (scope *Scope) autoMigrate() *Scope {
scope.Raw(fmt.Sprintf("ALTER TABLE %v ADD %v %v;", quotedTableName, field.DBName, field.SqlTag)).Exec() scope.Raw(fmt.Sprintf("ALTER TABLE %v ADD %v %v;", quotedTableName, field.DBName, field.SqlTag)).Exec()
} }
} }
scope.createJoinTable(field)
} }
} }
return scope return scope