fix: preload with skip hooks (#5310)
This commit is contained in:
		
							parent
							
								
									b0104943ed
								
							
						
					
					
						commit
						19b8d37ae8
					
				| @ -252,7 +252,7 @@ func Preload(db *gorm.DB) { | ||||
| 
 | ||||
| 		for _, name := range preloadNames { | ||||
| 			if rel := preloadDB.Statement.Schema.Relationships.Relations[name]; rel != nil { | ||||
| 				db.AddError(preload(preloadDB.Table("").Session(&gorm.Session{}), rel, append(db.Statement.Preloads[name], db.Statement.Preloads[clause.Associations]...), preloadMap[name])) | ||||
| 				db.AddError(preload(preloadDB.Table("").Session(&gorm.Session{Context: db.Statement.Context, SkipHooks: db.Statement.SkipHooks}), rel, append(db.Statement.Preloads[name], db.Statement.Preloads[clause.Associations]...), preloadMap[name])) | ||||
| 			} else { | ||||
| 				db.AddError(fmt.Errorf("%s: %w for schema %s", name, gorm.ErrUnsupportedRelation, db.Statement.Schema.Name)) | ||||
| 			} | ||||
|  | ||||
| @ -466,8 +466,9 @@ type Product4 struct { | ||||
| 
 | ||||
| type ProductItem struct { | ||||
| 	gorm.Model | ||||
| 	Code       string | ||||
| 	Product4ID uint | ||||
| 	Code               string | ||||
| 	Product4ID         uint | ||||
| 	AfterFindCallTimes int | ||||
| } | ||||
| 
 | ||||
| func (pi ProductItem) BeforeCreate(*gorm.DB) error { | ||||
| @ -477,6 +478,11 @@ func (pi ProductItem) BeforeCreate(*gorm.DB) error { | ||||
| 	return nil | ||||
| } | ||||
| 
 | ||||
| func (pi *ProductItem) AfterFind(*gorm.DB) error { | ||||
| 	pi.AfterFindCallTimes = pi.AfterFindCallTimes + 1 | ||||
| 	return nil | ||||
| } | ||||
| 
 | ||||
| func TestFailedToSaveAssociationShouldRollback(t *testing.T) { | ||||
| 	DB.Migrator().DropTable(&Product4{}, &ProductItem{}) | ||||
| 	DB.AutoMigrate(&Product4{}, &ProductItem{}) | ||||
| @ -498,4 +504,13 @@ func TestFailedToSaveAssociationShouldRollback(t *testing.T) { | ||||
| 	if err := DB.First(&Product4{}, "name = ?", product.Name).Error; err != nil { | ||||
| 		t.Errorf("should find product, but got error %v", err) | ||||
| 	} | ||||
| 
 | ||||
| 	var productWithItem Product4 | ||||
| 	if err := DB.Session(&gorm.Session{SkipHooks: true}).Preload("Item").First(&productWithItem, "name = ?", product.Name).Error; err != nil { | ||||
| 		t.Errorf("should find product, but got error %v", err) | ||||
| 	} | ||||
| 
 | ||||
| 	if productWithItem.Item.AfterFindCallTimes != 0 { | ||||
| 		t.Fatalf("AfterFind should not be called times:%d", productWithItem.Item.AfterFindCallTimes) | ||||
| 	} | ||||
| } | ||||
|  | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user
	 Cr
						Cr