fix: preload panic when model and dest different

This commit is contained in:
chenrui 2022-03-05 15:27:45 +08:00
parent b566ed7913
commit 7cbf019a93
2 changed files with 24 additions and 0 deletions

View File

@ -218,6 +218,13 @@ func Preload(db *gorm.DB) {
} }
sort.Strings(preloadNames) 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 { for _, name := range preloadNames {
if rel := db.Statement.Schema.Relationships.Relations[name]; rel != nil { 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]) preload(db, rel, append(db.Statement.Preloads[name], db.Statement.Preloads[clause.Associations]...), preloadMap[name])

View File

@ -251,3 +251,20 @@ func TestPreloadGoroutine(t *testing.T) {
} }
wg.Wait() 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)
}