From d047f854e66b669785cbe6be8227269807db1782 Mon Sep 17 00:00:00 2001 From: Adrien Carreira Date: Sat, 28 Aug 2021 10:27:19 +0200 Subject: [PATCH] PR Comments --- chainable_api.go | 15 +++++++++------ tests/joins_test.go | 4 ++-- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/chainable_api.go b/chainable_api.go index 184931ff..8fd7ee3c 100644 --- a/chainable_api.go +++ b/chainable_api.go @@ -171,15 +171,18 @@ func (db *DB) Or(query interface{}, args ...interface{}) (tx *DB) { // Joins specify Joins conditions // db.Joins("Account").Find(&user) // db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user) +// db.Joins("Account", DB.Select("id").Where("user_id = users.id AND name = ?", "someName").Model(&Account{})) func (db *DB) Joins(query string, args ...interface{}) (tx *DB) { tx = db.getInstance() - tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args}) - return -} -func (db *DB) JoinsOn(query string, on interface{}, args ...interface{}) (tx *DB) { - tx = db.getInstance() - tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args, On: on}) + if len(args) > 0 { + if db, ok := args[0].(*DB); ok { + tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args[1:], On: db}) + return + } + } + + tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args}) return } diff --git a/tests/joins_test.go b/tests/joins_test.go index 0b46d69c..21c73c19 100644 --- a/tests/joins_test.go +++ b/tests/joins_test.go @@ -111,14 +111,14 @@ func TestJoinOn(t *testing.T) { var user1 User onQuery := DB.Select("id").Where("user_id = users.id AND name = ?", "joins-on_pet_1").Model(&Pet{}) - if err := DB.JoinsOn("NamedPet", onQuery).Where("users.name = ?", user.Name).First(&user1).Error; err != nil { + if err := DB.Joins("NamedPet", onQuery).Where("users.name = ?", user.Name).First(&user1).Error; err != nil { t.Fatalf("Failed to load with joins on, got error: %v", err) } AssertEqual(t, user1.NamedPet.Name, "joins-on_pet_1") onQuery2 := DB.Select("id").Where("user_id = users.id AND name = ?", "joins-on_pet_2").Model(&Pet{}) var user2 User - if err := DB.JoinsOn("NamedPet", onQuery2).Where("users.name = ?", user.Name).First(&user2).Error; err != nil { + if err := DB.Joins("NamedPet", onQuery2).Where("users.name = ?", user.Name).First(&user2).Error; err != nil { t.Fatalf("Failed to load with joins on, got error: %v", err) } AssertEqual(t, user2.NamedPet.Name, "joins-on_pet_2")