Skip to content

Commit

Permalink
Add query->clear().
Browse files Browse the repository at this point in the history
I found a few duplicated blocks of code related to clearing query state
when subqueries are created. Having a function will help prevent code
getting out of sync in the future.
  • Loading branch information
markstory committed Sep 4, 2014
1 parent 8691204 commit 13b224c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 11 deletions.
7 changes: 2 additions & 5 deletions src/ORM/Association/SelectableAssociationTrait.php
Expand Up @@ -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') {
Expand Down
31 changes: 25 additions & 6 deletions src/ORM/Query.php
Expand Up @@ -467,19 +467,38 @@ 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.
*
* @return int
*/
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) {
Expand Down

2 comments on commit 13b224c

@spiliot
Copy link
Contributor

@spiliot spiliot commented on 13b224c Sep 6, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This commit seems to be breaking the following query in a controller:
$articles = $this->Articles->find()->where(['date' => $articleDate, 'Categories.title' => $catTitle]);
When $articles->count() is called the produced SQL doesn't include the Categories table and fails.

It was working up to this.

EDIT: The only difference between the old and new code is that the new one also clears containments.

@markstory
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting, do you have contained assoiations?

Please sign in to comment.