type Model1 struct {}

func (m *Model1) TableName() string {
    return "model1"
}

type Model2 struct {}

func (m *Model2) TableName() string {
    return "model2"
}

同一 db 实例,在使用一次查询后

db = db.Model(&Model1{}).Where(conditions1...) 

再次使用 db 进行查询 model2

db = db.Model(&Model2{}).Where(conditions2...)

此时,第二次的查询条件里,db.Statement.ModelModel2,但是 db.Statement.Table 依然为 model1,并且查询条件还携带了第一次查询的条件,导致查询错误。

SQL:

SELECT fields FROM `model1` WHERE conditions1 AND conditions2

使用最新版本。

不明白gorm的设计哲学,重新指定 model 不该重置所有查询条件,以及重置model吗,难道每次都要调用 db.Session 来生成新会话进行其他 model 的查询?

Comment From: henryjhenry

gorm 是否考虑过用 db.Model 或 db.Table 强制指定所查询的表,不该再在Find或其他终止方法里再去尝试获取查询的表,以此来降低复杂度提高可用性?

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking

Comment From: li-jin-gou

出现这个问题的主要原因在于 Gorm 会复用 statement 以此来提高性能,目前来看除了使用 .Session() 可以清除条件以外,还有一个使用方法建议: 每次在新的查询时去使用 DB 可以参考这个demo: https://github.com/cloudwego/hertz-examples/blob/main/bizdemo/hertz_gorm/biz/dal/mysql/user.go

文档可以参考: https://gorm.cn/zh_CN/docs/method_chaining.html#%E6%96%B9%E6%B3%95%E9%93%BE%E5%92%8C%E5%8D%8F%E7%A8%8B%E5%AE%89%E5%85%A8