From 67266ebdb3f7deb12c913104ef56ece51a83e193 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 9 Apr 2015 15:51:47 +0800 Subject: [PATCH] Fix create join table with multi primary keys --- scope_private.go | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/scope_private.go b/scope_private.go index 99dda2ed..03a47acc 100644 --- a/scope_private.go +++ b/scope_private.go @@ -445,13 +445,19 @@ func (scope *Scope) createJoinTable(field *StructField) { joinTableHandler := relationship.JoinTableHandler joinTable := joinTableHandler.Table(scope.db) if !scope.Dialect().HasTable(scope, joinTable) { - primaryKeySqlType := scope.Dialect().SqlTag(scope.PrimaryField().Field, 255, false) - scope.Err(scope.NewDB().Exec(fmt.Sprintf("CREATE TABLE %v (%v)", - scope.Quote(joinTable), - strings.Join([]string{ - scope.Quote(relationship.ForeignDBName) + " " + primaryKeySqlType, - scope.Quote(relationship.AssociationForeignDBName) + " " + primaryKeySqlType}, ",")), - ).Error) + toScope := &Scope{Value: reflect.New(field.Struct.Type).Interface()} + + var sqlTypes []string + for _, s := range []*Scope{scope, toScope} { + for _, primaryField := range s.GetModelStruct().PrimaryFields { + value := reflect.Indirect(reflect.New(primaryField.Struct.Type)) + 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) }