Fix create join table with multi primary keys

This commit is contained in:
Jinzhu 2015-04-09 15:51:47 +08:00
parent e2eef50fb4
commit 67266ebdb3
1 changed files with 13 additions and 7 deletions

View File

@ -445,13 +445,19 @@ func (scope *Scope) createJoinTable(field *StructField) {
joinTableHandler := relationship.JoinTableHandler joinTableHandler := relationship.JoinTableHandler
joinTable := joinTableHandler.Table(scope.db) joinTable := joinTableHandler.Table(scope.db)
if !scope.Dialect().HasTable(scope, joinTable) { if !scope.Dialect().HasTable(scope, joinTable) {
primaryKeySqlType := scope.Dialect().SqlTag(scope.PrimaryField().Field, 255, false) toScope := &Scope{Value: reflect.New(field.Struct.Type).Interface()}
scope.Err(scope.NewDB().Exec(fmt.Sprintf("CREATE TABLE %v (%v)",
scope.Quote(joinTable), var sqlTypes []string
strings.Join([]string{ for _, s := range []*Scope{scope, toScope} {
scope.Quote(relationship.ForeignDBName) + " " + primaryKeySqlType, for _, primaryField := range s.GetModelStruct().PrimaryFields {
scope.Quote(relationship.AssociationForeignDBName) + " " + primaryKeySqlType}, ",")), value := reflect.Indirect(reflect.New(primaryField.Struct.Type))
).Error) primaryKeySqlType := scope.Dialect().SqlTag(value, 255, false)
dbName := ToDBName(s.GetModelStruct().ModelType.Name() + primaryField.Name)
sqlTypes = append(sqlTypes, scope.Quote(dbName)+" "+primaryKeySqlType)
}
}
scope.Err(scope.NewDB().Exec(fmt.Sprintf("CREATE TABLE %v (%v)", scope.Quote(joinTable), strings.Join(sqlTypes, ","))).Error)
} }
scope.NewDB().Table(joinTable).AutoMigrate(joinTableHandler) scope.NewDB().Table(joinTable).AutoMigrate(joinTableHandler)
} }