From d483ffa45c51162ba9defe3a59c0ed62793c037f Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 15 Apr 2021 10:37:05 +0800 Subject: [PATCH] Fix Preload with nil pointer --- callbacks.go | 1 - callbacks/preload.go | 1 - tests/preload_test.go | 5 ++++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/callbacks.go b/callbacks.go index f2ee0ea5..ee96fcb9 100644 --- a/callbacks.go +++ b/callbacks.go @@ -110,7 +110,6 @@ func (p *processor) Execute(db *DB) { for stmt.ReflectValue.Kind() == reflect.Ptr { if stmt.ReflectValue.IsNil() && stmt.ReflectValue.CanAddr() { stmt.ReflectValue.Set(reflect.New(stmt.ReflectValue.Type().Elem())) - break } stmt.ReflectValue = stmt.ReflectValue.Elem() diff --git a/callbacks/preload.go b/callbacks/preload.go index eafd407d..25c5e659 100644 --- a/callbacks/preload.go +++ b/callbacks/preload.go @@ -27,7 +27,6 @@ func preload(db *gorm.DB, rel *schema.Relationship, conds []interface{}, preload }) if rel.JoinTable != nil { - var ( joinForeignFields = make([]*schema.Field, 0, len(rel.References)) joinRelForeignFields = make([]*schema.Field, 0, len(rel.References)) diff --git a/tests/preload_test.go b/tests/preload_test.go index c9f5d278..8f49955e 100644 --- a/tests/preload_test.go +++ b/tests/preload_test.go @@ -63,12 +63,15 @@ func TestNestedPreload(t *testing.T) { var user2 User DB.Preload("Pets.Toy").Find(&user2, "id = ?", user.ID) - CheckUser(t, user2, user) var user3 User DB.Preload(clause.Associations+"."+clause.Associations).Find(&user3, "id = ?", user.ID) CheckUser(t, user3, user) + + var user4 *User + DB.Preload("Pets.Toy").Find(&user4, "id = ?", user.ID) + CheckUser(t, *user4, user) } func TestNestedPreloadForSlice(t *testing.T) {