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
here is debug info, where condition of query2' is same as query1.
2025/01/08 09:40:20 D:/jjxu/work/demo/mytest/db/main.go:30
[2.614ms] [rows:0] SELECT * FROM `sys_user` WHERE id = 1
2025/01/08 09:40:20 D:/jjxu/work/demo/mytest/db/main.go:33
[3.182ms] [rows:0] SELECT * FROM `sys_user` WHERE id = 1
Usually, I writing it this way can resolve the issue.
This behavior is not a bug but an inherent characteristic of how GORM's query chaining and session handling work.
Why Does the WHERE Condition Disappear?
State Sharing Between Queries:
In GORM, when you create a new query object (e.g., query2 := query1.Session(&gorm.Session{})), it inherits the state of query1.
This inheritance includes shared query context but does not isolate the WHERE condition unless explicitly reset.
Chained Methods Don't Mutate Original Objects:
GORM's query-building methods (e.g., Where) return a new query object instead of mutating the original. If you don't capture the returned value, the new query object (with updated WHERE conditions) is lost, and the original query remains unchanged.
Your Code Example:
When you write query2.Where("id = 100"), it creates a new query object with the condition but doesn't reassign it to query2.
As a result, the original query2 is used in query2.Debug().Find(&data), and its WHERE condition is lost.
How to Fix This
To avoid such issues, always capture the return value when modifying queries:
Your Question
first, my codes like this
then,lock at the debug info, where condition is lost.
[11.136ms] [rows:1] SELECT * FROM `sys_user`
finally, I've noticed this phenomenon, and I'm not sure if it's a bug.
here is debug info, where condition of
query2
' is same asquery1
.Usually, I writing it this way can resolve the issue.
debug info:
[5.779ms] [rows:1] SELECT * FROM `sys_user` WHERE id =100
or
Expected answer
This issue can make it difficult for beginners to get started. If it's not a bug, I hope it should be reflected in the documentation.
The text was updated successfully, but these errors were encountered: