From 25ba9487aa744c5c484c16af15221b440a90c98c Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Fri, 31 Jul 2015 16:33:44 +0800 Subject: [PATCH] Create join table with computed foreign keys --- scope_private.go | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/scope_private.go b/scope_private.go index 1d58e6a2..e440f7a4 100644 --- a/scope_private.go +++ b/scope_private.go @@ -459,12 +459,19 @@ func (scope *Scope) createJoinTable(field *StructField) { 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)) + for idx, fieldName := range relationship.ForeignFieldNames { + if field, ok := scope.Fields()[fieldName]; ok { + value := reflect.Indirect(reflect.New(field.Struct.Type)) primaryKeySqlType := scope.Dialect().SqlTag(value, 255, false) - dbName := ToDBName(s.GetModelStruct().ModelType.Name() + primaryField.Name) - sqlTypes = append(sqlTypes, scope.Quote(dbName)+" "+primaryKeySqlType) + sqlTypes = append(sqlTypes, scope.Quote(relationship.ForeignDBNames[idx])+" "+primaryKeySqlType) + } + } + + for idx, fieldName := range relationship.AssociationForeignFieldNames { + if field, ok := toScope.Fields()[fieldName]; ok { + value := reflect.Indirect(reflect.New(field.Struct.Type)) + primaryKeySqlType := scope.Dialect().SqlTag(value, 255, false) + sqlTypes = append(sqlTypes, scope.Quote(relationship.AssociationForeignDBNames[idx])+" "+primaryKeySqlType) } }