You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Document that the combination of Where and Update (and possibly other combinations with Where) adds the ID of the entity to the where clause.
Example code:
type Model struct {
ID int
SomeColumn int
UpdatedAt *time.Time
}
func Update() {
model := &Model{SomeColumnValue: 1202547, id: 1234565}
updates := db.Where("some_column = ?", model.SomeColumn).Updates(&model)
// UPDATE "schema"."model" SET "id"=6850154, "updated_at"='2025-04-09 00:03:17.866' WHERE some_column = '1202547' AND "id" = '1234565'
}
Motivation
This came as a surprise during debugging of why some entities were not updated properly. It's undocumented, and not obvious to the user of the library.
The text was updated successfully, but these errors were encountered:
In GORM, when you update a model with a primary key (e.g., ID), it automatically adds the primary key to the WHERE clause for performance optimization. This ensures only the specific record is updated.
Solution:
If you don't want the primary key to be included in the WHERE clause, simply don't set the primary key (e.g., set ID to 0). When the primary key is zero, it won't be added to the WHERE clause.
Example:
model:=&Model{SomeColumn: 1202547}
db.Where("some_column = ?", model.SomeColumn).Updates(&model)
// UPDATE `models` SET `some_column`=1202547,`updated_at`='2025-05-07 09:14:02.939' WHERE some_column = 1202547
In this case, the primary key (ID) is not set, so GORM will not include it in the WHERE clause.
Describe the feature
Document that the combination of Where and Update (and possibly other combinations with Where) adds the ID of the entity to the where clause.
Example code:
Motivation
This came as a surprise during debugging of why some entities were not updated properly. It's undocumented, and not obvious to the user of the library.
The text was updated successfully, but these errors were encountered: