Skip to content

Commit

Permalink
Fix preload all associations with inline conditions, close go-gorm#4836
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Nov 8, 2021
1 parent b23c3b2 commit ca7accd
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
2 changes: 1 addition & 1 deletion callbacks/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down
13 changes: 13 additions & 0 deletions tests/preload_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit ca7accd

Please sign in to comment.