From ca7accdbf6b1ea1145c9342e661827b001c44f7a Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Mon, 8 Nov 2021 19:40:40 +0800 Subject: [PATCH] Fix preload all associations with inline conditions, close #4836 --- callbacks/query.go | 2 +- tests/preload_test.go | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/callbacks/query.go b/callbacks/query.go index 0cfb0b3f..6ca3a1fb 100644 --- a/callbacks/query.go +++ b/callbacks/query.go @@ -221,7 +221,7 @@ func Preload(db *gorm.DB) { for _, name := range preloadNames { if rel := db.Statement.Schema.Relationships.Relations[name]; rel != nil { - preload(db, rel, db.Statement.Preloads[name], preloadMap[name]) + preload(db, rel, append(db.Statement.Preloads[name], db.Statement.Preloads[clause.Associations]...), preloadMap[name]) } else { db.AddError(fmt.Errorf("%s: %w for schema %s", name, gorm.ErrUnsupportedRelation, db.Statement.Schema.Name)) } diff --git a/tests/preload_test.go b/tests/preload_test.go index 8f49955e..a3e67200 100644 --- a/tests/preload_test.go +++ b/tests/preload_test.go @@ -147,6 +147,19 @@ func TestPreloadWithConds(t *testing.T) { for i, u := range users3 { CheckUser(t, u, users[i]) } + + var user4 User + DB.Delete(&users3[0].Account) + + if err := DB.Preload(clause.Associations).Take(&user4, "id = ?", users3[0].ID).Error; err != nil || user4.Account.ID != 0 { + t.Errorf("failed to query, got error %v, account: %#v", err, user4.Account) + } + + if err := DB.Preload(clause.Associations, func(tx *gorm.DB) *gorm.DB { + return tx.Unscoped() + }).Take(&user4, "id = ?", users3[0].ID).Error; err != nil || user4.Account.ID == 0 { + t.Errorf("failed to query, got error %v, account: %#v", err, user4.Account) + } } func TestNestedPreloadWithConds(t *testing.T) {