Fix preload all associations with inline conditions, close #4836

This commit is contained in:
Jinzhu 2021-11-08 19:40:40 +08:00
parent b23c3b290e
commit ca7accdbf6
2 changed files with 14 additions and 1 deletions

View File

@ -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))
}

View File

@ -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) {