Add clause.JoinTable helper method

This commit is contained in:
Jinzhu 2025-04-20 20:08:07 +08:00
parent 797a557cc8
commit 4fcd909f2e
2 changed files with 11 additions and 2 deletions

View File

@ -1,5 +1,7 @@
package clause package clause
import "gorm.io/gorm/utils"
type JoinType string type JoinType string
const ( const (
@ -18,6 +20,12 @@ type Join struct {
Expression Expression Expression Expression
} }
func JoinTable(names ...string) Table {
return Table{
Name: utils.JoinNestedRelationNames(names),
}
}
func (join Join) Build(builder Builder) { func (join Join) Build(builder Builder) {
if join.Expression != nil { if join.Expression != nil {
join.Expression.Build(builder) join.Expression.Build(builder)

View File

@ -8,6 +8,7 @@ import (
"testing" "testing"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause"
. "gorm.io/gorm/utils/tests" . "gorm.io/gorm/utils/tests"
) )
@ -284,7 +285,7 @@ func TestGenericsJoinsAndPreload(t *testing.T) {
db.Create(ctx, &u) db.Create(ctx, &u)
// LEFT JOIN + WHERE // 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 { if err != nil {
t.Fatalf("Joins failed: %v", err) t.Fatalf("Joins failed: %v", err)
} }
@ -293,7 +294,7 @@ func TestGenericsJoinsAndPreload(t *testing.T) {
} }
// INNER JOIN + Inline WHERE // 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 { if err != nil {
t.Fatalf("InnerJoins failed: %v", err) t.Fatalf("InnerJoins failed: %v", err)
} }