From b3910291885dc02f756b4d2ae12baede9d555b0a Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sat, 28 Feb 2015 19:09:45 +0800 Subject: [PATCH] Fix stack overflow for many to many associations --- model_struct.go | 11 ++++++++--- structs_test.go | 5 +++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/model_struct.go b/model_struct.go index 25c8e50c..2a0ab743 100644 --- a/model_struct.go +++ b/model_struct.go @@ -195,7 +195,12 @@ func (scope *Scope) GetModelStruct() *ModelStruct { switch indirectType.Kind() { case reflect.Slice: - if toStructFields := toScope.GetStructFields(); len(toStructFields) > 0 { + elemType := indirectType.Elem() + if elemType.Kind() == reflect.Ptr { + elemType = elemType.Elem() + } + + if elemType.Kind() == reflect.Struct { if foreignKey == "" { foreignKey = scopeType.Name() + "Id" } @@ -206,7 +211,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct { associationForeignKey := gormSettings["ASSOCIATIONFOREIGNKEY"] if associationForeignKey == "" { - associationForeignKey = toScope.GetModelStruct().ModelType.Name() + "Id" + associationForeignKey = elemType.Name() + "Id" } relationship.ForeignFieldName = foreignKey @@ -216,7 +221,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct { field.Relationship = relationship } else { relationship.Kind = "has_many" - if foreignField := getForeignField(foreignKey, toStructFields); foreignField != nil { + if foreignField := getForeignField(foreignKey, toScope.GetStructFields()); foreignField != nil { relationship.ForeignFieldName = foreignField.Name relationship.ForeignDBName = foreignField.DBName foreignField.IsForeignKey = true diff --git a/structs_test.go b/structs_test.go index 3d864592..f52ef906 100644 --- a/structs_test.go +++ b/structs_test.go @@ -63,8 +63,9 @@ type Address struct { } type Language struct { - Id int - Name string + Id int + Name string + Users []User `gorm:"many2many:user_languages;"` } type Product struct {