Don't call AfterFind hooks if no record found, close #4048

This commit is contained in:
Jinzhu 2021-02-07 12:44:59 +08:00
parent bb153384d1
commit 4373aa01ab
2 changed files with 10 additions and 1 deletions

View File

@ -204,7 +204,7 @@ func Preload(db *gorm.DB) {
}
func AfterQuery(db *gorm.DB) {
if db.Error == nil && db.Statement.Schema != nil && !db.Statement.SkipHooks && db.Statement.Schema.AfterFind {
if db.Error == nil && db.Statement.Schema != nil && !db.Statement.SkipHooks && db.Statement.Schema.AfterFind && db.RowsAffected > 0 {
callMethod(db, func(value interface{}, tx *gorm.DB) bool {
if i, ok := value.(AfterFindInterface); ok {
db.AddError(i.AfterFind(tx))

View File

@ -133,6 +133,15 @@ func TestRunCallbacks(t *testing.T) {
if DB.Where("Code = ?", "unique_code").First(&p).Error == nil {
t.Fatalf("Can't find a deleted record")
}
beforeCallTimes := p.AfterFindCallTimes
if DB.Where("Code = ?", "unique_code").Find(&p).Error != nil {
t.Fatalf("Find don't raise error when record not found")
}
if p.AfterFindCallTimes != beforeCallTimes {
t.Fatalf("AfterFind should not be called")
}
}
func TestCallbacksWithErrors(t *testing.T) {