preload_m2m fix and test

This commit is contained in:
kimiby 2015-08-16 12:25:25 +03:00
parent fbce0d98f6
commit f35dee5531
2 changed files with 54 additions and 0 deletions

View File

@ -297,6 +297,22 @@ func (scope *Scope) handleHasManyToManyPreload(field *Field, conditions []interf
} }
} }
} }
} else {
object := scope.IndirectValue()
var checked []string
source := getRealValue(object, relation.AssociationForeignFieldNames)
for i := 0; i < results.Len(); i++ {
result := results.Index(i)
value := getRealValue(result, relation.ForeignFieldNames)
if strInSlice(toString(value), linkHash[toString(source)]) && !strInSlice(toString(value), checked) {
f := object.FieldByName(field.Name)
f.Set(reflect.Append(f, result))
checked = append(checked, toString(value))
continue
}
}
} }
} }

View File

@ -603,6 +603,44 @@ func TestNestedPreload9(t *testing.T) {
} }
} }
func TestManyToManyPreload(t *testing.T) {
type (
Level1 struct {
ID uint `gorm:"primary_key;"`
Value string
}
Level2 struct {
ID uint `gorm:"primary_key;"`
Value string
Level1s []Level1 `gorm:"many2many:levels;"`
}
)
DB.DropTableIfExists(&Level2{})
DB.DropTableIfExists(&Level1{})
if err := DB.AutoMigrate(&Level2{}, &Level1{}).Error; err != nil {
panic(err)
}
want := Level2{Value: "Bob", Level1s: []Level1{
Level1{Value: "ru"},
Level1{Value: "en"},
}}
if err := DB.Save(&want).Error; err != nil {
panic(err)
}
var got Level2
if err := DB.Preload("Level1s").Find(&got).Error; err != nil {
panic(err)
}
if !reflect.DeepEqual(got, want) {
t.Errorf("got %s; want %s", toJSONString(got), toJSONString(want))
}
}
func toJSONString(v interface{}) []byte { func toJSONString(v interface{}) []byte {
r, _ := json.MarshalIndent(v, "", " ") r, _ := json.MarshalIndent(v, "", " ")
return r return r