PR Comments

This commit is contained in:
Adrien Carreira 2021-08-28 10:27:19 +02:00 committed by Jinzhu
parent c301aeb524
commit d047f854e6
2 changed files with 11 additions and 8 deletions

View File

@ -171,15 +171,18 @@ func (db *DB) Or(query interface{}, args ...interface{}) (tx *DB) {
// Joins specify Joins conditions // Joins specify Joins conditions
// db.Joins("Account").Find(&user) // 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("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) { func (db *DB) Joins(query string, args ...interface{}) (tx *DB) {
tx = db.getInstance() tx = db.getInstance()
tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args})
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 return
} }
}
func (db *DB) JoinsOn(query string, on interface{}, args ...interface{}) (tx *DB) { tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args})
tx = db.getInstance()
tx.Statement.Joins = append(tx.Statement.Joins, join{Name: query, Conds: args, On: on})
return return
} }

View File

@ -111,14 +111,14 @@ func TestJoinOn(t *testing.T) {
var user1 User var user1 User
onQuery := DB.Select("id").Where("user_id = users.id AND name = ?", "joins-on_pet_1").Model(&Pet{}) 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) t.Fatalf("Failed to load with joins on, got error: %v", err)
} }
AssertEqual(t, user1.NamedPet.Name, "joins-on_pet_1") 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{}) onQuery2 := DB.Select("id").Where("user_id = users.id AND name = ?", "joins-on_pet_2").Model(&Pet{})
var user2 User 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) t.Fatalf("Failed to load with joins on, got error: %v", err)
} }
AssertEqual(t, user2.NamedPet.Name, "joins-on_pet_2") AssertEqual(t, user2.NamedPet.Name, "joins-on_pet_2")