Fix to call Scopes with using Migrator

This commit is contained in:
Jinzhu 2021-03-19 16:34:51 +08:00
parent a9fe025ef5
commit 8c92d9694a
2 changed files with 16 additions and 5 deletions

View File

@ -7,16 +7,18 @@ import (
// Migrator returns migrator
func (db *DB) Migrator() Migrator {
tx := db.getInstance()
// apply scopes to migrator
for len(db.Statement.scopes) > 0 {
scopes := db.Statement.scopes
db.Statement.scopes = nil
for len(tx.Statement.scopes) > 0 {
scopes := tx.Statement.scopes
tx.Statement.scopes = nil
for _, scope := range scopes {
db = scope(db)
tx = scope(tx)
}
}
return db.Dialector.Migrator(db.Session(&Session{}))
return tx.Dialector.Migrator(tx.Session(&Session{}))
}
// AutoMigrate run auto migration for given models

View File

@ -45,4 +45,13 @@ func TestScopes(t *testing.T) {
if len(users3) != 2 {
t.Errorf("Should found two users's name in 1, 3, but got %v", len(users3))
}
db := DB.Scopes(func(tx *gorm.DB) *gorm.DB {
return tx.Table("custom_table")
}).Session(&gorm.Session{})
db.AutoMigrate(&User{})
if db.Find(&User{}).Statement.Table != "custom_table" {
t.Errorf("failed to call Scopes")
}
}