Fix Join condition with DB, close #4719

This commit is contained in:
Jinzhu 2021-09-28 21:43:12 +08:00
parent 6864a24150
commit 002bf78ea7
2 changed files with 7 additions and 1 deletions

View File

@ -179,8 +179,8 @@ func (db *DB) Joins(query string, args ...interface{}) (tx *DB) {
if db, ok := args[0].(*DB); ok {
if where, ok := db.Statement.Clauses["WHERE"].Expression.(clause.Where); ok {
tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args[1:], On: &where})
return
}
return
}
}

View File

@ -102,6 +102,12 @@ func TestJoinConds(t *testing.T) {
if !regexp.MustCompile("SELECT .* FROM .users. left join pets.*join accounts.*").MatchString(stmt.SQL.String()) {
t.Errorf("joins should be ordered, but got %v", stmt.SQL.String())
}
iv := DB.Table(`table_invoices`).Select(`seller, SUM(total) as total, SUM(paid) as paid, SUM(balance) as balance`).Group(`seller`)
stmt = dryDB.Table(`table_employees`).Select(`id, name, iv.total, iv.paid, iv.balance`).Joins(`LEFT JOIN (?) AS iv ON iv.seller = table_employees.id`, iv).Scan(&user).Statement
if !regexp.MustCompile("SELECT id, name, iv.total, iv.paid, iv.balance FROM .table_employees. LEFT JOIN \\(SELECT seller, SUM\\(total\\) as total, SUM\\(paid\\) as paid, SUM\\(balance\\) as balance FROM .table_invoices. GROUP BY .seller.\\) AS iv ON iv.seller = table_employees.id").MatchString(stmt.SQL.String()) {
t.Errorf("joins should be ordered, but got %v", stmt.SQL.String())
}
}
func TestJoinOn(t *testing.T) {