Skip to content

Association doesn't replace the entities with new ones and throw an error. #5899

@MuhmdHsn313

Description

@MuhmdHsn313

GORM Playground Link

go-gorm/playground#548

Description

I have two tables Item and ItemContent:

type Item struct {
	gorm.Model
	Logo        string                `json:"logo" gorm:"not null;type:varchar(50)"`
	Contents    []ItemContent       `json:"contents" gorm:"foreignKey:ItemID"`
}

type ItemContent struct {
	gorm.Model
	ItemID   uint     `json:"item_id" gorm:"not null"`
	Name       string   `json:"name" gorm:"not null;type:varchar(50)"`
	LanguageCode string   `json:"language_code" gorm:"not null;type:varchar(2)"`
}

I tried to insert a new Item and ItemContent into the SQLite database:

item := model.Item{
		Logo: "logo",
		Contents: []model.ItemContent{
			{
				LanguageCode: "en",
				Name:       "name",
			},
			{
				LanguageCode: "ar",
				Name:       "الاسم",
			},
		},
	}
db.Create(&item)

after creating a new Item I needed to replace the contents with new contents using Association in gorm, I wrote this code for replacing by calling Association.Replace method. It should remove the previous contents and set these new contents:

db.Model(&item).Association("Contents").Replace([]model.ItemContent{
		{
			LanguageCode: "en",
			Name:       "updated name",
		},
		{
			LanguageCode : "ar",
			Name:       "الاسم المحدث",
		},
		{
			LanguageCode : "fr",
			Name:       "le nom",
		},
	})

but there is an error occurred when I call the Association.Replace code:

sqlite3.Error{
    code: 19,
    extendedCode: 1299,
    systemErrno: golang.org/x/sys/windows.ERROR_SUCCESS (0),
    err: NOT NULL constraint failed: vendor_contents.vendor_id
}

after that I opened the sqlite3 database and I find a new 3 rows has been added into item_contents table without removing the previous 2 rows, so there is 5 rows in the table. I expected that the Association.Replace removed the existing 2 rows and add the new 3 rows.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions