From 38a24606da3cd1e312644ef5f8d71e4d0d35554a Mon Sep 17 00:00:00 2001 From: huangcheng1 Date: Sat, 2 Apr 2022 17:27:53 +0800 Subject: [PATCH] fix: tables lost when joins exists in from clause, close #5218 commit 7f6a603afa26820e187489b5203f93adc513687c Author: Jinzhu Date: Sat Apr 2 17:26:48 2022 +0800 Refactor #5218 commit 95d00e6ff2668233f3eca98aa4917291e3d869bd Author: huangcheng1 Date: Fri Apr 1 16:30:27 2022 +0800 fix: tables lost when joins exists in from clause --- callbacks/query.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/callbacks/query.go b/callbacks/query.go index 6eda52ef4..fb2bb37ad 100644 --- a/callbacks/query.go +++ b/callbacks/query.go @@ -96,12 +96,12 @@ func BuildQuerySQL(db *gorm.DB) { } // inline joins - joins := []clause.Join{} - if fromClause, ok := db.Statement.Clauses["FROM"].Expression.(clause.From); ok { - joins = fromClause.Joins + fromClause := clause.From{} + if v, ok := db.Statement.Clauses["FROM"].Expression.(clause.From); ok { + fromClause = v } - if len(db.Statement.Joins) != 0 || len(joins) != 0 { + if len(db.Statement.Joins) != 0 || len(fromClause.Joins) != 0 { if len(db.Statement.Selects) == 0 && len(db.Statement.Omits) == 0 && db.Statement.Schema != nil { clauseSelect.Columns = make([]clause.Column, len(db.Statement.Schema.DBNames)) for idx, dbName := range db.Statement.Schema.DBNames { @@ -111,7 +111,7 @@ func BuildQuerySQL(db *gorm.DB) { for _, join := range db.Statement.Joins { if db.Statement.Schema == nil { - joins = append(joins, clause.Join{ + fromClause.Joins = append(fromClause.Joins, clause.Join{ Expression: clause.NamedExpr{SQL: join.Name, Vars: join.Conds}, }) } else if relation, ok := db.Statement.Schema.Relationships.Relations[join.Name]; ok { @@ -176,19 +176,19 @@ func BuildQuerySQL(db *gorm.DB) { } } - joins = append(joins, clause.Join{ + fromClause.Joins = append(fromClause.Joins, clause.Join{ Type: clause.LeftJoin, Table: clause.Table{Name: relation.FieldSchema.Table, Alias: tableAliasName}, ON: clause.Where{Exprs: exprs}, }) } else { - joins = append(joins, clause.Join{ + fromClause.Joins = append(fromClause.Joins, clause.Join{ Expression: clause.NamedExpr{SQL: join.Name, Vars: join.Conds}, }) } } - db.Statement.AddClause(clause.From{Joins: joins}) + db.Statement.AddClause(fromClause) db.Statement.Joins = nil } else { db.Statement.AddClauseIfNotExists(clause.From{})