preoload not allowd before count (#5023)
Co-authored-by: ningfei <accelerator314@outlook.com>
This commit is contained in:
		
							parent
							
								
									c0bea447b9
								
							
						
					
					
						commit
						8c3673286d
					
				| @ -39,4 +39,6 @@ var ( | |||||||
| 	ErrInvalidValue = errors.New("invalid value, should be pointer to struct or slice") | 	ErrInvalidValue = errors.New("invalid value, should be pointer to struct or slice") | ||||||
| 	// ErrInvalidValueOfLength invalid values do not match length
 | 	// ErrInvalidValueOfLength invalid values do not match length
 | ||||||
| 	ErrInvalidValueOfLength = errors.New("invalid association values, length doesn't match") | 	ErrInvalidValueOfLength = errors.New("invalid association values, length doesn't match") | ||||||
|  | 	// ErrPreloadNotAllowed preload is not allowed when count is used
 | ||||||
|  | 	ErrPreloadNotAllowed = errors.New("preload is not allowed when count is used") | ||||||
| ) | ) | ||||||
|  | |||||||
| @ -367,6 +367,10 @@ func (db *DB) Delete(value interface{}, conds ...interface{}) (tx *DB) { | |||||||
| 
 | 
 | ||||||
| func (db *DB) Count(count *int64) (tx *DB) { | func (db *DB) Count(count *int64) (tx *DB) { | ||||||
| 	tx = db.getInstance() | 	tx = db.getInstance() | ||||||
|  | 	if len(tx.Statement.Preloads) > 0 { | ||||||
|  | 		tx.AddError(ErrPreloadNotAllowed) | ||||||
|  | 		return | ||||||
|  | 	} | ||||||
| 	if tx.Statement.Model == nil { | 	if tx.Statement.Model == nil { | ||||||
| 		tx.Statement.Model = tx.Statement.Dest | 		tx.Statement.Model = tx.Statement.Dest | ||||||
| 		defer func() { | 		defer func() { | ||||||
|  | |||||||
| @ -144,4 +144,14 @@ func TestCount(t *testing.T) { | |||||||
| 	if err := DB.Model(&User{}).Where("name = ?", "count-4").Group("name").Count(&count11).Error; err != nil || count11 != 1 { | 	if err := DB.Model(&User{}).Where("name = ?", "count-4").Group("name").Count(&count11).Error; err != nil || count11 != 1 { | ||||||
| 		t.Fatalf("Count should be 3, but got count: %v err %v", count11, err) | 		t.Fatalf("Count should be 3, but got count: %v err %v", count11, err) | ||||||
| 	} | 	} | ||||||
|  | 
 | ||||||
|  | 	var count12 int64 | ||||||
|  | 	if err := DB.Table("users"). | ||||||
|  | 		Where("name in ?", []string{user1.Name, user2.Name, user3.Name}). | ||||||
|  | 		Preload("Toys", func(db *gorm.DB) *gorm.DB { | ||||||
|  | 			return db.Table("toys").Select("name") | ||||||
|  | 		}).Count(&count12).Error; err != gorm.ErrPreloadNotAllowed { | ||||||
|  | 		t.Errorf("should returns preload not allowed error, but got %v", err) | ||||||
|  | 	} | ||||||
|  | 	 | ||||||
| } | } | ||||||
|  | |||||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user
	 Ning
						Ning