Skip to content

Commit

Permalink
fix: association without pks (#5779)
Browse files Browse the repository at this point in the history
  • Loading branch information
a631807682 committed Oct 18, 2022
1 parent 2a788fb commit 186e8a9
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
10 changes: 8 additions & 2 deletions callbacks/associations.go
Expand Up @@ -208,7 +208,10 @@ func SaveAfterAssociations(create bool) func(db *gorm.DB) {

cacheKey := utils.ToStringKey(relPrimaryValues...)
if len(relPrimaryValues) != len(rel.FieldSchema.PrimaryFields) || !identityMap[cacheKey] {
identityMap[cacheKey] = true
if cacheKey != "" { // has primary fields
identityMap[cacheKey] = true
}

if isPtr {
elems = reflect.Append(elems, elem)
} else {
Expand Down Expand Up @@ -294,7 +297,10 @@ func SaveAfterAssociations(create bool) func(db *gorm.DB) {

cacheKey := utils.ToStringKey(relPrimaryValues...)
if len(relPrimaryValues) != len(rel.FieldSchema.PrimaryFields) || !identityMap[cacheKey] {
identityMap[cacheKey] = true
if cacheKey != "" { // has primary fields
identityMap[cacheKey] = true
}

distinctElems = reflect.Append(distinctElems, elem)
}

Expand Down
42 changes: 42 additions & 0 deletions tests/associations_test.go
Expand Up @@ -348,3 +348,45 @@ func TestAssociationEmptyQueryClause(t *testing.T) {
AssertEqual(t, len(orgs), 0)
}
}

type AssociationEmptyUser struct {
ID uint
Name string
Pets []AssociationEmptyPet
}

type AssociationEmptyPet struct {
AssociationEmptyUserID *uint `gorm:"uniqueIndex:uniq_user_id_name"`
Name string `gorm:"uniqueIndex:uniq_user_id_name;size:256"`
}

func TestAssociationEmptyPrimaryKey(t *testing.T) {
if DB.Dialector.Name() != "mysql" {
t.Skip()
}
DB.Migrator().DropTable(&AssociationEmptyUser{}, &AssociationEmptyPet{})
DB.AutoMigrate(&AssociationEmptyUser{}, &AssociationEmptyPet{})

id := uint(100)
user := AssociationEmptyUser{
ID: id,
Name: "jinzhu",
Pets: []AssociationEmptyPet{
{AssociationEmptyUserID: &id, Name: "bar"},
{AssociationEmptyUserID: &id, Name: "foo"},
},
}

err := DB.Session(&gorm.Session{FullSaveAssociations: true}).Create(&user).Error
if err != nil {
t.Fatalf("Failed to create, got error: %v", err)
}

var result AssociationEmptyUser
err = DB.Preload("Pets").First(&result, &id).Error
if err != nil {
t.Fatalf("Failed to find, got error: %v", err)
}

AssertEqual(t, result, user)
}

0 comments on commit 186e8a9

Please sign in to comment.