From 3fe7fcf35683fcd14209f0f7da13a378078b0b6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nico=20Sch=C3=A4fer?= Date: Wed, 12 Jun 2024 12:00:47 +0200 Subject: [PATCH] fix: `unsupported data` on nested joins with preloads (#6957) * fix: `unsupported data` on nested joins with preloads * Add test case for pointer join with nested prelaods * Fix tests --- callbacks/preload.go | 2 +- tests/preload_test.go | 52 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/callbacks/preload.go b/callbacks/preload.go index 112343fa..3dd0dea3 100644 --- a/callbacks/preload.go +++ b/callbacks/preload.go @@ -140,7 +140,7 @@ func preloadEntryPoint(db *gorm.DB, joins []string, relationships *schema.Relati return err } } - case reflect.Struct: + case reflect.Struct, reflect.Pointer: reflectValue := rel.Field.ReflectValueOf(db.Statement.Context, rv) tx := preloadDB(db, reflectValue, reflectValue.Interface()) if err := preloadEntryPoint(tx, nestedJoins, &tx.Statement.Schema.Relationships, preloadMap[name], associationsConds); err != nil { diff --git a/tests/preload_test.go b/tests/preload_test.go index 6e0e91ba..f798b5f4 100644 --- a/tests/preload_test.go +++ b/tests/preload_test.go @@ -440,6 +440,58 @@ func TestMergeNestedPreloadWithNestedJoin(t *testing.T) { } } +func TestNestedPreloadWithPointerJoin(t *testing.T) { + type ( + Preload struct { + ID uint + Value string + JoinID uint + } + Join struct { + ID uint + Value string + Preload Preload + NestedID uint + } + Nested struct { + ID uint + Join Join + ValueID uint + } + Value struct { + ID uint + Name string + Nested *Nested + } + ) + + DB.Migrator().DropTable(&Preload{}, &Join{}, &Nested{}, &Value{}) + DB.Migrator().AutoMigrate(&Preload{}, &Join{}, &Nested{}, &Value{}) + + value := Value{ + Name: "value", + Nested: &Nested{ + Join: Join{ + Value: "j1", + Preload: Preload{ + Value: "p1", + }, + }, + }, + } + + if err := DB.Create(&value).Error; err != nil { + t.Errorf("failed to create value, got err: %v", err) + } + + var find1 Value + err := DB.Table("values").Joins("Nested").Joins("Nested.Join").Preload("Nested.Join.Preload").First(&find1).Error + if err != nil { + t.Errorf("failed to find value, got err: %v", err) + } + AssertEqual(t, find1, value) +} + func TestEmbedPreload(t *testing.T) { type Country struct { ID int `gorm:"primaryKey"`