From 8c98ce8c7f1b1c1c8d03f774a8c66ef7fc4619a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=91=E6=9E=97?= Date: Tue, 9 Nov 2021 13:58:08 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ActiveQuery.php | 4 +--- src/SqlBuilder.php | 12 +++++++----- src/Traits/Builder.php | 6 +++++- 3 files changed, 13 insertions(+), 9 deletions(-) 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 *"; }