allow configuring select/omit columns for joins via subqueries
This commit is contained in:
parent
d073805c86
commit
ba94e4eb2f
10
generics.go
10
generics.go
@ -256,6 +256,16 @@ func (c chainG[T]) Joins(jt clause.JoinTarget, args func(db QueryInterface, join
|
||||
joinType = clause.LeftJoin
|
||||
}
|
||||
|
||||
if db, ok := jt.Subquery.(interface{ getInstance() *DB }); ok {
|
||||
stmt := db.getInstance().Statement
|
||||
if len(j.Selects) == 0 {
|
||||
j.Selects = stmt.Selects
|
||||
}
|
||||
if len(j.Omits) == 0 {
|
||||
j.Omits = stmt.Omits
|
||||
}
|
||||
}
|
||||
|
||||
expr := clause.NamedExpr{SQL: fmt.Sprintf("%s JOIN (?) AS ?", joinType), Vars: []interface{}{jt.Subquery, clause.Table{Name: j.Alias}}}
|
||||
|
||||
if j.On != nil {
|
||||
|
@ -342,7 +342,23 @@ func TestGenericsJoinsAndPreload(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Raw subquery join failed: %v", err)
|
||||
}
|
||||
if result.Name != u2.Name || result.Company.Name != u.Company.Name {
|
||||
if result.Name != u2.Name || result.Company.Name != u.Company.Name || result.Company.ID == 0 {
|
||||
t.Fatalf("Joins expected %s, got %+v", u.Name, result)
|
||||
}
|
||||
|
||||
// Raw Subquery JOIN + WHERE + Select
|
||||
result, err = db.Joins(clause.LeftJoin.AssociationFrom("Company", gorm.G[Company](DB).Select("Name")).As("t"),
|
||||
func(db gorm.QueryInterface, joinTable clause.Table, curTable clause.Table) gorm.QueryInterface {
|
||||
if joinTable.Name != "t" {
|
||||
t.Fatalf("Join table should be t, but got %v", joinTable.Name)
|
||||
}
|
||||
return db.Where("?.name = ?", joinTable, u.Company.Name)
|
||||
},
|
||||
).Where(map[string]any{"name": u2.Name}).First(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("Raw subquery join failed: %v", err)
|
||||
}
|
||||
if result.Name != u2.Name || result.Company.Name != u.Company.Name || result.Company.ID != 0 {
|
||||
t.Fatalf("Joins expected %s, got %+v", u.Name, result)
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user