diff --git a/src/ORM/Association/SelectableAssociationTrait.php b/src/ORM/Association/SelectableAssociationTrait.php index 6ffb8f0a4cd..b80974a19f8 100644 --- a/src/ORM/Association/SelectableAssociationTrait.php +++ b/src/ORM/Association/SelectableAssociationTrait.php @@ -160,11 +160,8 @@ protected abstract function _linkField($options); */ protected function _buildSubquery($query) { $filterQuery = clone $query; - $filterQuery->autoFields(false); - $filterQuery->limit(null); - $filterQuery->offset(null); - $filterQuery->order([], true); - $filterQuery->contain([], true); + $filterQuery->clear(); + $joins = $filterQuery->join(); foreach ($joins as $i => $join) { if (strtolower($join['type']) !== 'inner') { diff --git a/src/ORM/Query.php b/src/ORM/Query.php index ec83aff0f4c..fcec8e527c9 100644 --- a/src/ORM/Query.php +++ b/src/ORM/Query.php @@ -467,6 +467,29 @@ public function applyOptions(array $options) { return $this; } +/** + * Clear many the clauses that will make cloned queries behave incorrectly. + * + * The following clauses/features will be cleared: + * + * - autoFields + * - limit + * - offset + * - map/reduce functions + * - result formatters + * - order + * - containments + */ + public function clear() { + $this->autoFields(false); + $this->limit(null); + $this->order([], true); + $this->offset(null); + $this->mapReduce(null, null, true); + $this->formatResults(null, true); + $this->contain([], true); + } + /** * Returns the COUNT(*) for the query. * @@ -474,12 +497,8 @@ public function applyOptions(array $options) { */ public function count() { $query = clone $this; - $query->autoFields(false); - $query->limit(null); - $query->order([], true); - $query->offset(null); - $query->mapReduce(null, null, true); - $query->formatResults(null, true); + $query->clear(); + $counter = $this->_counter; if ($counter) {