gorm icon indicating copy to clipboard operation
gorm copied to clipboard

Count() erases SELECTs for Joins() statement if executed before a Find()

Open dschreij opened this issue 1 year ago • 2 comments

GORM Playground Link

https://github.com/go-gorm/playground/pull/681

Description

If you add a Joins() preload statement to a *gorm.DB transaction instance, the select statements to loads field from the relationship seems to be nullified if you first call tx.Count() and then afterwards with the same tx also call tx.Find(). The tx.Find() no longer selects the fields from the joined tables, e.g.

var res []MyModel
tx := db.Model(&MyModel)
tx.Joins("OtherModel")
var cnt *int64
tx.Count(&cnt)
tx.Find(&res)
// res.OtherModel.<somefield> is empty as SELECT for OtherModels have disappeared from the query

A use case for this scenario is if you are paginating: You first want to get the total records in the DB to show in the UI (or calculate the amount of pages) and after doing so, you apply a limit and offset to the tx to obtain a subset of the results.

If you call the join statements again, this results in an error:

var res []MyModel
tx := db.Model(&MyModel)
tx.Joins("OtherModel")
var cnt *int64
tx.Count(&cnt)
tx.Joins("OtherModel")
tx.Find(&res)

pq: table name \"OtherModel\" specified more than once

dschreij avatar Jan 10 '24 15:01 dschreij

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

github-actions[bot] avatar Jan 10 '24 15:01 github-actions[bot]

我也有相同的问题。 调用count()后,会删除joins。这和预期的不一样,我理解的应该不会删除。如图 image

执行count的时候db的 joins 里面有2个 成员 image

执行到find的时候,joins变成了nil image

但是查看执行的语句又是对的 image 这点就很奇怪

kissIce avatar Feb 02 '24 02:02 kissIce