#7812·gorm

Generics API: allow JoinTarget to override association join table

Author: kifril-ltdCreated Jun 19, 2026Updated Sep 19, 2026
Labelstype:with reproduction steps

GORM Playground Link

https://github.com/go-gorm/playground/pull/854

Related issue: https://github.com/go-gorm/gorm/issues/7745

Description

I am migrating a schema-per-tenant PostgreSQL application to the Generics API. The root table can be selected per query:

go
gorm.G[Order](db).Table("tenant_1.orders")

The playground PR uses SQLite ATTACH DATABASE to keep the reproduction self-contained, but the issue is about schema-qualified association joins in general.

But association joins still use the table name from the cached relation schema:

go
type Order struct {
    ID         int64
    CustomerID int64
    Customer   Customer `gorm:"foreignKey:CustomerID"`
}

type Customer struct {
    ID int64
}

gorm.G[Order](db).
    Table("tenant_1.orders").
    Joins(clause.InnerJoin.Association("Customer"), nil).
    Find(ctx)

Current SQL:

sql
FROM "tenant_1"."orders"
INNER JOIN "customers" "Customer" ON ...

Expected SQL:

sql
FROM "tenant_1"."orders"
INNER JOIN "tenant_1"."customers" "Customer" ON ...

JoinTarget.Table does not solve this because As(name) writes to the same field and the Generics API uses it as the association alias. The physical table for association joins is still built from relation.FieldSchema.Table.

The current workaround is to use AssociationFrom with a subquery:

go
gorm.G[Order](db).
    Table("tenant_1.orders").
    Joins(
        clause.InnerJoin.AssociationFrom(
            "Customer",
            clause.Expr{SQL: "SELECT * FROM tenant_1.customers"},
        ).As("Customer"),
        nil,
    ).
    Find(ctx)

This works, but it forces a plain table join to be wrapped as a subquery only to override the physical table.

Proposed API

Add an optional physical table override to clause.JoinTarget:

go
clause.JoinTarget{
    Type:        clause.InnerJoin,
    Association: "Customer",
    From:        clause.Table{Name: "tenant_1.customers", Alias: "Customer"},
}

From would override only the physical joined table. Table/As would keep their current alias behavior.

If From is not set, GORM would keep the current behavior and use relation.FieldSchema.Table, so this should be backward compatible.

The association metadata, selected association columns, and JoinBuilder ON conditions would still come from Association as they do today.