preoload not allowd before count (#5023)

Co-authored-by: ningfei <accelerator314@outlook.com>
This commit is contained in:
Ning 2022-01-30 18:17:06 +08:00 committed by GitHub
parent c0bea447b9
commit 8c3673286d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 16 additions and 0 deletions

View File

@ -39,4 +39,6 @@ var (
ErrInvalidValue = errors.New("invalid value, should be pointer to struct or slice")
// ErrInvalidValueOfLength invalid values do not match length
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")
)

View File

@ -367,6 +367,10 @@ func (db *DB) Delete(value interface{}, conds ...interface{}) (tx *DB) {
func (db *DB) Count(count *int64) (tx *DB) {
tx = db.getInstance()
if len(tx.Statement.Preloads) > 0 {
tx.AddError(ErrPreloadNotAllowed)
return
}
if tx.Statement.Model == nil {
tx.Statement.Model = tx.Statement.Dest
defer func() {

View File

@ -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 {
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)
}
}