From b13732c450770779dde472dd71da3344461d9602 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 13 Jul 2021 20:23:05 +0800 Subject: [PATCH] Fix invalid preload SQL when no data found, close #4443 --- callbacks/preload.go | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/callbacks/preload.go b/callbacks/preload.go index 25c5e659..47986ff1 100644 --- a/callbacks/preload.go +++ b/callbacks/preload.go @@ -104,15 +104,17 @@ func preload(db *gorm.DB, rel *schema.Relationship, conds []interface{}, preload reflectResults := rel.FieldSchema.MakeSlice().Elem() column, values := schema.ToQueryValues(clause.CurrentTable, relForeignKeys, foreignValues) - for _, cond := range conds { - if fc, ok := cond.(func(*gorm.DB) *gorm.DB); ok { - tx = fc(tx) - } else { - inlineConds = append(inlineConds, cond) + if len(values) != 0 { + for _, cond := range conds { + if fc, ok := cond.(func(*gorm.DB) *gorm.DB); ok { + tx = fc(tx) + } else { + inlineConds = append(inlineConds, cond) + } } - } - db.AddError(tx.Where(clause.IN{Column: column, Values: values}).Find(reflectResults.Addr().Interface(), inlineConds...).Error) + db.AddError(tx.Where(clause.IN{Column: column, Values: values}).Find(reflectResults.Addr().Interface(), inlineConds...).Error) + } fieldValues := make([]interface{}, len(relForeignFields))