Skip to content

Commit

Permalink
fix: tables lost when joins exists in from clause, close #5218
Browse files Browse the repository at this point in the history
commit 7f6a603afa26820e187489b5203f93adc513687c
Author: Jinzhu <wosmvp@gmail.com>
Date:   Sat Apr 2 17:26:48 2022 +0800

    Refactor #5218

commit 95d00e6
Author: huangcheng1 <huangcheng1@sensetime.com>
Date:   Fri Apr 1 16:30:27 2022 +0800

    fix: tables lost when joins exists in from clause
  • Loading branch information
chein-huang authored and jinzhu committed Apr 2, 2022
1 parent 9144969 commit 38a2460
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions callbacks/query.go
Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down Expand Up @@ -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{})
Expand Down

0 comments on commit 38a2460

Please sign in to comment.