diff --git a/src/ActiveQuery.php b/src/ActiveQuery.php index 4e52883..622378a 100644 --- a/src/ActiveQuery.php +++ b/src/ActiveQuery.php @@ -237,9 +237,7 @@ class ActiveQuery extends Component implements ISqlBuilder */ public function count(): int { - $clone = clone $this; - $clone->select = ['COUNT(*)']; - $data = $this->execute($clone->builder->count())->one(); + $data = $this->execute($this->builder->count())->one(); if ($data && is_array($data)) { return (int)array_shift($data); } diff --git a/src/SqlBuilder.php b/src/SqlBuilder.php index ad16bf8..204a176 100644 --- a/src/SqlBuilder.php +++ b/src/SqlBuilder.php @@ -240,7 +240,7 @@ class SqlBuilder extends Component if (empty($this->query->from) && !empty($this->query->modelClass)) { $this->query->from($this->query->getTable()); } - return $this->_prefix(); + return $this->_prefix(false, true); } @@ -256,14 +256,15 @@ class SqlBuilder extends Component /** * @param bool $hasOrder + * @param bool $isCount * @return string * @throws Exception */ - private function _prefix(bool $hasOrder = false): string + private function _prefix(bool $hasOrder = false, bool $isCount = false): string { $select = ''; if (!empty($this->query->from)) { - $select = $this->_selectPrefix(); + $select = $this->_selectPrefix($isCount); } $select = $this->_wherePrefix($select); if (!empty($this->query->attributes) && is_array($this->query->attributes)) { @@ -302,12 +303,13 @@ class SqlBuilder extends Component /** + * @param bool $isCount * @return string * @throws Exception */ - private function _selectPrefix(): string + private function _selectPrefix(bool $isCount): string { - $select = $this->builderSelect($this->query->select) . ' FROM ' . $this->tableName(); + $select = $this->builderSelect($this->query->select, $isCount) . ' FROM ' . $this->tableName(); if (!empty($this->query->alias)) { $select .= $this->builderAlias($this->query->alias); } diff --git a/src/Traits/Builder.php b/src/Traits/Builder.php index 55e6827..0dc642c 100644 --- a/src/Traits/Builder.php +++ b/src/Traits/Builder.php @@ -61,10 +61,14 @@ trait Builder /** * @param null $select + * @param bool $isCount * @return string */ - #[Pure] private function builderSelect($select = NULL): string + #[Pure] private function builderSelect($select = NULL, bool $isCount = false): string { + if ($isCount) { + return "SELECT COUNT(*)"; + } if (empty($select)) { return "SELECT *"; }