Skip to content

Assciations Replace method might be mishandling the mix of existing and new records #7432

@apuatcfbd

Description

@apuatcfbd

GORM Playground Link

The playground link is time-consuming. Right now I can't do that :(.

Description

Gorm associations Replace method might be mishandling the mix of existing and new records. Following is the models

// Post model
type Post struct {
	// ...

	// relations //
	Images []Media `json:"image" gorm:"polymorphic:Owner;"`
}

// Media model
type Media struct {
	ID uint `json:"id" gorm:"primaryKey"`

	// ...

	OwnerID   uint   `json:"owner_id" gorm:"not null;"`
	OwnerType string `json:"owner_type" gorm:"not null;"`
}

Now, let's assume Post (id: 1) has 3 images. The last record on media table is 10.
When I tried to add another image with

// omit error checks for simplicity
m := database.DB.Preload("Images").First(m, 1) // Post model with all images (has 3)

images := make([]model.Media, 0) // create final images slice
// 1. add images from fetched post model 
// 2. filter out the images if wanted to delete some, In this case lets assume no deletion
// 3. Add newly added images

img := createImgFromPaylod() // returns Media model (made up, the Id is 0)
images = append(images, *md)

// at this stage len(images) == 4. 3 existing one + new 1

// now we want to replace (with hard deleteion) updated images for the post
tx.Unscoped().Model(m).Association("Images").Unscoped().Replace(images) // inside a transaction

// This completes successfully. The problem is -
// when db is manually inspected, (remember last record's ID in media table was `10`)
// It is visible that one record is added, but the ID is `13` !! (note: db auto increment for Id field is 1)
// when the expected ID was `11`

Why this happening? I'm not absolutely sure if this is a Gorm bug or i'm doing something wrong.
I'll be thankful if you let me know if I'm doing something wrong

Info:
Go 1.23.1
gorm.io/driver/mysql v1.5.7
gorm.io/gorm v1.25.12

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions