go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
36.52k stars 3.91k forks source link

Scope not working in combination with callback #6505

Open tsdevelopment opened 1 year ago

tsdevelopment commented 1 year ago

Your Question

I added a custom callback and wanted to use a scope in. Bute the scope will not be called as expected. See the following code with different fmt.Println outputs:

// Add callback
db.Callback().Query().Before("gorm:query").Register("app:query:custom", customCallback)

// Custom callback function that calls a scope
func customCallback(db *gorm.DB) {
    fmt.Println("customCallback 1")
    db.Scopes(customScope("myVar"))
}

// Custom scope that also could be used in any other query.
func customScope(myVar string) func(db *gorm.DB) *gorm.DB {
    fmt.Println("customScope 1")
    return func(db *gorm.DB) *gorm.DB {
        fmt.Println("customScope 2")
        return db.Where("foo = ?", myVar)
    }
}

I would expect the following output:

# customCallback 1
# customScope 1
# customScope 2

but the last output is missing. I only see

# customCallback 1
# customScope 1

The document you expected this should be explained

https://gorm.io/docs/scopes.html https://gorm.io/docs/write_plugins.html#Callbacks

Expected answer

Would be good to know if the behavoiur is correct and / or it is possible to use scopes in callbacks or not.

tsdevelopment commented 11 months ago

@jinzhu is this behaviour correct or must it be fixed?