diff --git a/README.md b/README.md index 6d467f9a..0a1463c0 100644 --- a/README.md +++ b/README.md @@ -1012,11 +1012,8 @@ for rows.Next() { db.Table("users").Select("users.name, emails.email").Joins("left join emails on emails.user_id = users.id").Scan(&results) -// find a user by email address -db.Joins("inner join emails on emails.user_id = users.id").Where("emails.email = ?", "x@example.org").Find(&user) - -// find all email addresses for a user -db.Joins("LEFT JOIN users ON users.id = emails.user_id AND users.name = ?", "jinzhu").Find(&emails) +// multiple joins with parameter +db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Joins("JOIN credit_cards ON credit_cards.user_id = users.id").Where("credit_cards.number = ?", "411111111111").Find(&user) ``` ## Transactions diff --git a/main_test.go b/main_test.go index 39189cd3..dff91828 100644 --- a/main_test.go +++ b/main_test.go @@ -501,8 +501,9 @@ func TestGroup(t *testing.T) { func TestJoins(t *testing.T) { var user = User{ - Name: "joins", - Emails: []Email{{Email: "join1@example.com"}, {Email: "join2@example.com"}}, + Name: "joins", + CreditCard: CreditCard{Number: "411111111111"}, + Emails: []Email{{Email: "join1@example.com"}, {Email: "join2@example.com"}}, } DB.Save(&user) @@ -517,6 +518,18 @@ func TestJoins(t *testing.T) { if len(users2) != 1 { t.Errorf("should find one users using left join with conditions") } + + var users3 []User + DB.Joins("join emails on emails.user_id = users.id AND emails.email = ?", "join1@example.com").Joins("join credit_cards on credit_cards.user_id = users.id AND credit_cards.number = ?", "411111111111").Where("name = ?", "joins").First(&users3) + if len(users3) != 1 { + t.Errorf("should find one users using multiple left join conditions") + } + + var users4 []User + DB.Joins("join emails on emails.user_id = users.id AND emails.email = ?", "join1@example.com").Joins("join credit_cards on credit_cards.user_id = users.id AND credit_cards.number = ?", "422222222222").Where("name = ?", "joins").First(&users4) + if len(users4) != 0 { + t.Errorf("should find no user when searching with unexisting credit card") + } } func TestJoinsWithSelect(t *testing.T) {