From 407bedae0a529f8512b44522b319aa8434249dee Mon Sep 17 00:00:00 2001 From: Cr <631807682@qq.com> Date: Wed, 26 Apr 2023 22:19:32 +0800 Subject: [PATCH] fix: nested joins alias (#6265) --- callbacks/query.go | 7 ++++++- tests/joins_test.go | 16 ++++++++++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/callbacks/query.go b/callbacks/query.go index 95db1f0a..e89dd199 100644 --- a/callbacks/query.go +++ b/callbacks/query.go @@ -234,7 +234,12 @@ func BuildQuerySQL(db *gorm.DB) { fromClause.Joins = append(fromClause.Joins, genJoinClause(join.JoinType, parentTableName, rel)) specifiedRelationsName[nestedAlias] = nil } - parentTableName = rel.Name + + if parentTableName != clause.CurrentTable { + parentTableName = utils.NestedRelationName(parentTableName, rel.Name) + } else { + parentTableName = rel.Name + } } } else { fromClause.Joins = append(fromClause.Joins, clause.Join{ diff --git a/tests/joins_test.go b/tests/joins_test.go index e6715bbe..786fc37e 100644 --- a/tests/joins_test.go +++ b/tests/joins_test.go @@ -329,8 +329,19 @@ func TestJoinArgsWithDB(t *testing.T) { func TestNestedJoins(t *testing.T) { users := []User{ { - Name: "nested-joins-1", - Manager: GetUser("nested-joins-manager-1", Config{Company: true, NamedPet: true}), + Name: "nested-joins-1", + Manager: &User{ + Name: "nested-joins-manager-1", + Company: Company{ + Name: "nested-joins-manager-company-1", + }, + NamedPet: &Pet{ + Name: "nested-joins-manager-namepet-1", + Toy: Toy{ + Name: "nested-joins-manager-namepet-toy-1", + }, + }, + }, NamedPet: &Pet{Name: "nested-joins-namepet-1", Toy: Toy{Name: "nested-joins-namepet-toy-1"}}, }, { @@ -352,6 +363,7 @@ func TestNestedJoins(t *testing.T) { Joins("Manager"). Joins("Manager.Company"). Joins("Manager.NamedPet"). + Joins("Manager.NamedPet.Toy"). Joins("NamedPet"). Joins("NamedPet.Toy"). Find(&users2, "users.id IN ?", userIDs).Error; err != nil {