Fix Count after Session

This commit is contained in:
Jinzhu 2020-06-23 22:41:41 +08:00
parent 4201f7bdab
commit 7e1fa4a44d
2 changed files with 10 additions and 2 deletions

View File

@ -284,8 +284,8 @@ func (db *DB) Count(count *int64) (tx *DB) {
tx.Statement.Dest = count
tx.callbacks.Query().Execute(tx)
if db.RowsAffected != 1 {
*count = db.RowsAffected
if tx.RowsAffected != 1 {
*count = tx.RowsAffected
}
return
}

View File

@ -4,6 +4,7 @@ import (
"fmt"
"testing"
"gorm.io/gorm"
. "gorm.io/gorm/utils/tests"
)
@ -31,6 +32,13 @@ func TestCount(t *testing.T) {
t.Errorf("multiple count in chain should works")
}
tx := DB.Model(&User{}).Where("name = ?", user1.Name).Session(&gorm.Session{WithConditions: true})
tx.Count(&count1)
tx.Or("name in ?", []string{user2.Name, user3.Name}).Count(&count2)
if count1 != 1 || count2 != 3 {
t.Errorf("count after new session should works")
}
var count3 int64
if err := DB.Model(&User{}).Where("name in ?", []string{user2.Name, user2.Name, user3.Name}).Group("id").Count(&count3).Error; err != nil {
t.Errorf("Error happened when count with group, but got %v", err)