From 4fcd909f2e04d9dd03b46d1fd04ffc8131d41c10 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sun, 20 Apr 2025 20:08:07 +0800 Subject: [PATCH] Add clause.JoinTable helper method --- clause/joins.go | 8 ++++++++ tests/generics_test.go | 5 +++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/clause/joins.go b/clause/joins.go index 879892be..b0f0359c 100644 --- a/clause/joins.go +++ b/clause/joins.go @@ -1,5 +1,7 @@ package clause +import "gorm.io/gorm/utils" + type JoinType string const ( @@ -18,6 +20,12 @@ type Join struct { Expression Expression } +func JoinTable(names ...string) Table { + return Table{ + Name: utils.JoinNestedRelationNames(names), + } +} + func (join Join) Build(builder Builder) { if join.Expression != nil { join.Expression.Build(builder) diff --git a/tests/generics_test.go b/tests/generics_test.go index 1587d090..c467f9ff 100644 --- a/tests/generics_test.go +++ b/tests/generics_test.go @@ -8,6 +8,7 @@ import ( "testing" "gorm.io/gorm" + "gorm.io/gorm/clause" . "gorm.io/gorm/utils/tests" ) @@ -284,7 +285,7 @@ func TestGenericsJoinsAndPreload(t *testing.T) { db.Create(ctx, &u) // LEFT JOIN + WHERE - result, err := db.Joins("Company").Where("Company.name = ?", u.Company.Name).First(ctx) + result, err := db.Joins("Company").Where("?.name = ?", clause.JoinTable("Company"), u.Company.Name).First(ctx) if err != nil { t.Fatalf("Joins failed: %v", err) } @@ -293,7 +294,7 @@ func TestGenericsJoinsAndPreload(t *testing.T) { } // INNER JOIN + Inline WHERE - result2, err := db.InnerJoins("Company", "Company.name = ?", u.Company.Name).First(ctx) + result2, err := db.InnerJoins("Company", "?.name = ?", clause.JoinTable("Company"), u.Company.Name).First(ctx) if err != nil { t.Fatalf("InnerJoins failed: %v", err) }