Don't call AfterFind hooks if no record found, close #4048
This commit is contained in:
		
							parent
							
								
									bb153384d1
								
							
						
					
					
						commit
						4373aa01ab
					
				| @ -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)) | ||||
|  | ||||
| @ -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) { | ||||
|  | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user
	 Jinzhu
						Jinzhu