Skip to content

Document Where().Update() behaviour #7422

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
ziemerz opened this issue Apr 14, 2025 · 1 comment
Open

Document Where().Update() behaviour #7422

ziemerz opened this issue Apr 14, 2025 · 1 comment
Assignees
Labels
type:feature_request feature request

Comments

@ziemerz
Copy link

ziemerz commented Apr 14, 2025

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:

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.

@github-actions github-actions bot added the type:feature_request feature request label Apr 14, 2025
@zwell
Copy link

zwell commented May 7, 2025

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type:feature_request feature request
Projects
None yet
Development

No branches or pull requests

3 participants