From 002bf78ea787f1df8ef3dd084e4854a9da8fedce Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 28 Sep 2021 21:43:12 +0800 Subject: [PATCH] Fix Join condition with DB, close #4719 --- chainable_api.go | 2 +- tests/joins_test.go | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/chainable_api.go b/chainable_api.go index 01ab2597..23e60110 100644 --- a/chainable_api.go +++ b/chainable_api.go @@ -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 } } diff --git a/tests/joins_test.go b/tests/joins_test.go index e560f38a..25fa20b4 100644 --- a/tests/joins_test.go +++ b/tests/joins_test.go @@ -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) {