GORM Playground Link

https://github.com/go-gorm/playground/pull/527

Description

There are some related issues but issue still exist.

5220

5221

5126

type Pet struct {
        // There is no primary key
    UserID *uint  `gorm:"uniqueIndex:uniq_user_id_name"`
    Name   string `gorm:"uniqueIndex:uniq_user_id_name;size:256"`
}
user := User{
    Model: gorm.Model{
        ID: userID,
    },
    Name: "jinzhu",
    Pets: []*Pet{
        {UserID: &userID, Name: "foo"},
        {UserID: &userID, Name: "bar"},
    },
}

Before v.1.22.5, the create statement of the above model is

INSERT INTO `pets` (`user_id`,`name`) VALUES (1024,'foo'), (1024, 'bar') ON DUPLICATE KEY UPDATE `user_id`=VALUES(`user_id`),`name`=VALUES(`name`)

But since the commit 8627634959401e4126d12a6d18f3aa8249a036ef, it only insert one row.

INSERT INTO `pets` (`user_id`,`name`) VALUES (1024,'foo') ON DUPLICATE KEY UPDATE `user_id`=VALUES(`user_id`),`name`=VALUES(`name`)

Debug

This only occurs when the associated model does not have a primary key.

// The cacheKey is [] because the relPrimaryValues is a empty slice.
cacheKey := utils.ToStringKey(relPrimaryValues)

In the first loop, the cacheKey [] is stored in the identityMap. So the rest of the loop is skipped.

How to fix

This issue can be avoided by set a primary key. But for the guys upgrading to v1.22.5, without a primary key, the system behavior changed. Is there a better way to deal with the problem?

Comment From: karelp90

I'm having same issue and replace is not working as expected

Comment From: milosrs

This issue is still active, even with the fix. Have a look at this issue: #5826 @jinzhu