Test multiple Joins

This commit is contained in:
Jinzhu 2016-02-21 10:52:30 +08:00
parent 29f3e6a927
commit f57198fe97
2 changed files with 17 additions and 7 deletions

View File

@ -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) 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 // multiple joins with parameter
db.Joins("inner join emails on emails.user_id = users.id").Where("emails.email = ?", "x@example.org").Find(&user) 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)
// find all email addresses for a user
db.Joins("LEFT JOIN users ON users.id = emails.user_id AND users.name = ?", "jinzhu").Find(&emails)
``` ```
## Transactions ## Transactions

View File

@ -501,8 +501,9 @@ func TestGroup(t *testing.T) {
func TestJoins(t *testing.T) { func TestJoins(t *testing.T) {
var user = User{ var user = User{
Name: "joins", Name: "joins",
Emails: []Email{{Email: "join1@example.com"}, {Email: "join2@example.com"}}, CreditCard: CreditCard{Number: "411111111111"},
Emails: []Email{{Email: "join1@example.com"}, {Email: "join2@example.com"}},
} }
DB.Save(&user) DB.Save(&user)
@ -517,6 +518,18 @@ func TestJoins(t *testing.T) {
if len(users2) != 1 { if len(users2) != 1 {
t.Errorf("should find one users using left join with conditions") 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) { func TestJoinsWithSelect(t *testing.T) {