GORM Playground Link

https://github.com/go-gorm/playground/pull/430

Description

The same execution via Scopes() gives different SQL.

tx.Where("name = ?", "jinzhu").Where(tx.Where("age = ?", 2).Or("age = ?", 3)).Find(&user)

is executing

SELECT * FROM `users` WHERE name = "jinzhu" AND (age = 2 OR age = 3) AND `users`.`deleted_at` IS NULL

while

scopesFunction := func(db *gorm.DB) *gorm.DB {
    return db.Where("name = ?", "jinzhu").Where(db.Where("age = ?", 2).Or("age = ?", 3))
}
tx.Scopes(scopesFunction).Find(&user)

is executing as

SELECT * FROM `users` WHERE (name = "jinzhu" AND age = 2 OR age = 3 AND (name = "jinzhu" AND age = 2 OR age = 3)) AND `users`.`deleted_at` IS NULL

I would expect the same sql being executed.

This does not happen if the without enclosed Where statements:

Where("name = ?", "jinzhu").Find(&user)

does execute the same in both cases.

Comment From: li-jin-gou

hello @frankr5 the problem arises because the statement is reused here and you can refer to this document https://gorm.cn/docs/method_chaining.html

func TestGORM(t *testing.T) {
    user := User{Name: "jinzhu"}

    scopesFunction := func(db *gorm.DB) *gorm.DB {
        return db.Where("name = ?", "jinzhu").Where(DB.Where("age = ?", 2).Or("age = ?", 3))
    }
    DB.Scopes(scopesFunction).Find(&user)
}

result:

[3.414ms] [rows:0] SELECT * FROM `users` WHERE name = 'jinzhu' AND (age = 2 OR age = 3) AND `users`.`deleted_at` IS