mirror of https://github.com/go-gorm/gorm.git
preload_m2m fix and test
This commit is contained in:
parent
fbce0d98f6
commit
f35dee5531
16
preload.go
16
preload.go
|
@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -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
|
||||||
|
|
Loading…
Reference in New Issue