Refactor cascade delete associations
This commit is contained in:
		
							parent
							
								
									06d534d6ea
								
							
						
					
					
						commit
						a932175ccf
					
				| @ -2,6 +2,7 @@ package callbacks | ||||
| 
 | ||||
| import ( | ||||
| 	"reflect" | ||||
| 	"strings" | ||||
| 
 | ||||
| 	"gorm.io/gorm" | ||||
| 	"gorm.io/gorm/clause" | ||||
| @ -37,7 +38,18 @@ func DeleteBeforeAssociations(db *gorm.DB) { | ||||
| 							withoutConditions := false | ||||
| 
 | ||||
| 							if len(db.Statement.Selects) > 0 { | ||||
| 								tx = tx.Select(db.Statement.Selects) | ||||
| 								var selects []string | ||||
| 								for _, s := range db.Statement.Selects { | ||||
| 									if s == clause.Associations { | ||||
| 										selects = append(selects, s) | ||||
| 									} else if strings.HasPrefix(s, column+".") { | ||||
| 										selects = append(selects, strings.TrimPrefix(s, column+".")) | ||||
| 									} | ||||
| 								} | ||||
| 
 | ||||
| 								if len(selects) > 0 { | ||||
| 									tx = tx.Select(selects) | ||||
| 								} | ||||
| 							} | ||||
| 
 | ||||
| 							for _, cond := range queryConds { | ||||
|  | ||||
| @ -136,7 +136,7 @@ func TestDeleteWithAssociations(t *testing.T) { | ||||
| 		t.Fatalf("failed to create user, got error %v", err) | ||||
| 	} | ||||
| 
 | ||||
| 	if err := DB.Select(clause.Associations).Delete(&user).Error; err != nil { | ||||
| 	if err := DB.Select(clause.Associations, "Pets.Toy").Delete(&user).Error; err != nil { | ||||
| 		t.Fatalf("failed to delete user, got error %v", err) | ||||
| 	} | ||||
| 
 | ||||
|  | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user
	 Jinzhu
						Jinzhu