Skip to content

Gorm doesnt allow updates of ids whose relations have been preloaded #7616

@Fuzzyma

Description

@Fuzzyma

GORM Playground Link

go-gorm/playground#834

Description

I spend multiple hours trying to figure out why a simple Save() wasnt working after I set some relation Ids to new values.

Turns out, when you preloaded the relation of that id field before, gorm does not allow to update the id.
It will reflect it in the struct, but will reset it back after while Save(). When using nullable fields with pointers, this also means, that the pointer is changed back to the old value which can lead to sideeffects when the pointer is used somewhere else.

In my case a simple settings.StateID = &state.ID lead to absolutely unexpected behavior.

I understand, that gorm does not want to get the preloaded model and the id out of sync but silently reverting it on save is even worse.

I would have expected an error that tells me the missmatch or just save the id without updating relations.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions