diff --git a/callbacks/query.go b/callbacks/query.go index 05b572f0..5a97e1ad 100644 --- a/callbacks/query.go +++ b/callbacks/query.go @@ -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)) diff --git a/tests/hooks_test.go b/tests/hooks_test.go index fe3f7d08..0e6ab2fe 100644 --- a/tests/hooks_test.go +++ b/tests/hooks_test.go @@ -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) {