fix: AfterQuery should clear FROM Clause's Joins rather than the Statement (#7027)

This commit is contained in:
贾一饼 2024-06-12 17:51:44 +08:00 committed by GitHub
parent 49d524aaea
commit 9c4070ed19
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 10 additions and 4 deletions

View File

@ -286,7 +286,11 @@ func Preload(db *gorm.DB) {
func AfterQuery(db *gorm.DB) {
// clear the joins after query because preload need it
db.Statement.Joins = nil
if v, ok := db.Statement.Clauses["FROM"].Expression.(clause.From); ok {
fromClause := db.Statement.Clauses["FROM"]
fromClause.Expression = clause.From{Tables: v.Tables, Joins: v.Joins[:len(v.Joins)-len(db.Statement.Joins)]} // keep the original From Joins
db.Statement.Clauses["FROM"] = fromClause
}
if db.Error == nil && db.Statement.Schema != nil && !db.Statement.SkipHooks && db.Statement.Schema.AfterFind && db.RowsAffected > 0 {
callMethod(db, func(value interface{}, tx *gorm.DB) bool {
if i, ok := value.(AfterFindInterface); ok {

View File

@ -184,14 +184,12 @@ func TestJoinCount(t *testing.T) {
DB.Create(&user)
query := DB.Model(&User{}).Joins("Company")
// Bug happens when .Count is called on a query.
// Removing the below two lines or downgrading to gorm v1.20.12 will make this test pass.
var total int64
query.Count(&total)
var result User
// Incorrectly generates a 'SELECT *' query which causes companies.id to overwrite users.id
if err := query.First(&result, user.ID).Error; err != nil {
t.Fatalf("Failed, got error: %v", err)
}
@ -199,6 +197,10 @@ func TestJoinCount(t *testing.T) {
if result.ID != user.ID {
t.Fatalf("result's id, %d, doesn't match user's id, %d", result.ID, user.ID)
}
// should find company
if result.Company.ID != *user.CompanyID {
t.Fatalf("result's id, %d, doesn't match user's company id, %d", result.Company.ID, *user.CompanyID)
}
}
func TestJoinWithSoftDeleted(t *testing.T) {