Your Question
I have a BaseModel that has a GetDefaultFilters method. All my models implement BaseModel. GetDefaultFilters returns some default filters that must be injected in the where clause of every query on that model. How do I enforce this through hooks?
I used the before query hook, and it worked beautifully but that gets executed only for a few functions like Find, First etc. When I use Scan, it gets skipped.
If this is not possible, is there a way to only allow Find on these models?
The document you expected this should be explained
https://gorm.io/docs/hooks.html
Expected answer
Comment From: trtuandat98
Hi, You can use GORM Callbacks like below
queryCallback := db.Callback().Query()
queryCallback.Before("gorm:query").Register("yourcallbackname", func(db *gorm.DB) {
// Check your model
// ...
// Add default filter
db.Clauses(clause.Where{})
})
Here is default defined callbacks: https://github.com/go-gorm/gorm/blob/master/callbacks/callbacks.go
If you use Scan, you can do the same with callback gorm:row