diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md index 0b47bc2ffa..f06aa02afd 100644 --- a/framework/CHANGELOG.md +++ b/framework/CHANGELOG.md @@ -21,6 +21,7 @@ Yii Framework 2 Change Log - Bug #8012: Fixed fetching multiple relations between two tables for pgsql (nineinchnick) - Bug #8014: Fixed setting incorrect form "action" property after submitting a form using a link with "data-method" and containing "action" among "data-params" (samdark) - Bug #8032: `yii\rbac\PhpManager::updateItem()` was unable to rename item updated (ChristopheBrun, samdark) +- Bug #8068: Fixed `yii\db\Query::count()` fails for query containing 'having' without 'group by' (klimov-paul) - Enh #3376: Added `yii\validators\EachValidator`, which allows validation of the array attributes (klimov-paul) - Enh #6895: Added `ignoreCategories` config option for message command to ignore categories specified (samdark) - Enh #6975: Pressing arrows while focused in inputs of Active Form with `validateOnType` enabled no longer triggers validation (slinstj) diff --git a/framework/db/Query.php b/framework/db/Query.php index 7bc35d1f44..d55dbc47a6 100644 --- a/framework/db/Query.php +++ b/framework/db/Query.php @@ -385,7 +385,7 @@ class Query extends Component implements QueryInterface $this->limit = $limit; $this->offset = $offset; - if (empty($this->groupBy) && empty($this->union) && !$this->distinct) { + if (empty($this->groupBy) && empty($this->having) && empty($this->union) && !$this->distinct) { return $command->queryScalar(); } else { return (new Query)->select([$selectExpression]) diff --git a/tests/unit/framework/db/QueryTest.php b/tests/unit/framework/db/QueryTest.php index deb57e1dce..b94f7dec2b 100644 --- a/tests/unit/framework/db/QueryTest.php +++ b/tests/unit/framework/db/QueryTest.php @@ -205,4 +205,35 @@ class QueryTest extends DatabaseTestCase ->column($db); $this->assertEquals([3 => 'user3', 2 => 'user2', 1 => 'user1'], $result); } + + public function testCount() + { + $db = $this->getConnection(); + + $count = (new Query)->from('customer')->count('*', $db); + $this->assertEquals(3, $count); + + $count = (new Query)->from('customer')->where(['status' => 2])->count('*', $db); + $this->assertEquals(1, $count); + + $count = (new Query)->from('customer')->groupBy('status')->count('*', $db); + $this->assertEquals(2, $count); + } + + /** + * @see https://github.com/yiisoft/yii2/issues/8068 + * + * @depends testCount + */ + public function testCountHaving() + { + if (in_array($this->driverName, ['sqlite'])) { + $this->markTestSkipped("{$this->driverName} does not support having without group by."); + } + + $db = $this->getConnection(); + + $count = (new Query)->from('customer')->having(['status' => 2])->count('*', $db); + $this->assertEquals(1, $count); + } }