Fix stack overflow for many to many associations

This commit is contained in:
Jinzhu 2015-02-28 19:09:45 +08:00
parent 4e8d43dd4f
commit b391029188
2 changed files with 11 additions and 5 deletions

View File

@ -195,7 +195,12 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
switch indirectType.Kind() { switch indirectType.Kind() {
case reflect.Slice: 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 == "" { if foreignKey == "" {
foreignKey = scopeType.Name() + "Id" foreignKey = scopeType.Name() + "Id"
} }
@ -206,7 +211,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
associationForeignKey := gormSettings["ASSOCIATIONFOREIGNKEY"] associationForeignKey := gormSettings["ASSOCIATIONFOREIGNKEY"]
if associationForeignKey == "" { if associationForeignKey == "" {
associationForeignKey = toScope.GetModelStruct().ModelType.Name() + "Id" associationForeignKey = elemType.Name() + "Id"
} }
relationship.ForeignFieldName = foreignKey relationship.ForeignFieldName = foreignKey
@ -216,7 +221,7 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
field.Relationship = relationship field.Relationship = relationship
} else { } else {
relationship.Kind = "has_many" relationship.Kind = "has_many"
if foreignField := getForeignField(foreignKey, toStructFields); foreignField != nil { if foreignField := getForeignField(foreignKey, toScope.GetStructFields()); foreignField != nil {
relationship.ForeignFieldName = foreignField.Name relationship.ForeignFieldName = foreignField.Name
relationship.ForeignDBName = foreignField.DBName relationship.ForeignDBName = foreignField.DBName
foreignField.IsForeignKey = true foreignField.IsForeignKey = true

View File

@ -65,6 +65,7 @@ type Address struct {
type Language struct { type Language struct {
Id int Id int
Name string Name string
Users []User `gorm:"many2many:user_languages;"`
} }
type Product struct { type Product struct {