From 7cbf019a930019476a97ac7ac0f5fc186e8d5b42 Mon Sep 17 00:00:00 2001 From: chenrui Date: Sat, 5 Mar 2022 15:27:45 +0800 Subject: [PATCH] fix: preload panic when model and dest different --- callbacks/query.go | 7 +++++++ tests/preload_test.go | 17 +++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/callbacks/query.go b/callbacks/query.go index 03798859..e6794119 100644 --- a/callbacks/query.go +++ b/callbacks/query.go @@ -218,6 +218,13 @@ func Preload(db *gorm.DB) { } sort.Strings(preloadNames) + // different schema + if db.Statement.ReflectValue.CanAddr() && db.Statement.Dest != db.Statement.Model { + if err := db.Statement.Parse(db.Statement.Dest); err != nil { + db.AddError(err) + } + } + for _, name := range preloadNames { if rel := db.Statement.Schema.Relationships.Relations[name]; rel != nil { preload(db, rel, append(db.Statement.Preloads[name], db.Statement.Preloads[clause.Associations]...), preloadMap[name]) diff --git a/tests/preload_test.go b/tests/preload_test.go index adb54ee1..b18b7d77 100644 --- a/tests/preload_test.go +++ b/tests/preload_test.go @@ -251,3 +251,20 @@ func TestPreloadGoroutine(t *testing.T) { } wg.Wait() } + +func TestPreloadWithDiffModel(t *testing.T) { + user := *GetUser("preload_with_diff_model", Config{Account: true}) + + if err := DB.Create(&user).Error; err != nil { + t.Fatalf("errors happened when create: %v", err) + } + + CheckUser(t, user, user) + + var result struct { + Something string + User + } + DB.Model(&User{}).Select("users.*, 'yo' as something").Preload("Account").Find(&result, user.ID) + CheckUser(t, user, result.User) +}