Skip to content
This repository
Browse code

Even less queries

  • Loading branch information...
commit e92e3df2fbf996e7058787057ac9734a39f50737 1 parent 8ea0212
Andy Dawson authored March 25, 2013

Showing 1 changed file with 29 additions and 13 deletions. Show diff stats Hide diff stats

  1. 42  lib/Cake/Model/Behavior/TreeBehavior.php
42  lib/Cake/Model/Behavior/TreeBehavior.php
@@ -654,14 +654,6 @@ public function recover(Model $Model, $mode = 'parent', $missingParentAction = n
654 654
  * @return integer $counter
655 655
  */
656 656
 	protected function _recoverByParentId(Model $Model, $counter = 1, $parentId = null) {
657  
-		if (!is_null($parentId)) {
658  
-			$Model->updateAll(
659  
-				array($this->settings[$Model->alias]['left'] => $counter),
660  
-				array($Model->escapeField() => $parentId)
661  
-			);
662  
-			$counter++;
663  
-		}
664  
-
665 657
 		$params = array(
666 658
 			'conditions' => array(
667 659
 				$this->settings[$Model->alias]['parent'] => $parentId
@@ -677,17 +669,41 @@ protected function _recoverByParentId(Model $Model, $counter = 1, $parentId = nu
677 669
 			$conditions[] = $scope;
678 670
 		}
679 671
 
680  
-		while ($rows = $Model->find('all', $params)) {
681  
-			foreach ($rows as $row) {
  672
+		$children = $Model->find('all', $params);
  673
+		$hasChildren = (bool)$children;
  674
+
  675
+		if (!is_null($parentId)) {
  676
+			if($hasChildren) {
  677
+				$Model->updateAll(
  678
+					array($this->settings[$Model->alias]['left'] => $counter),
  679
+					array($Model->escapeField() => $parentId)
  680
+				);
  681
+				$counter++;
  682
+			} else {
  683
+				$Model->updateAll(
  684
+					array(
  685
+						$this->settings[$Model->alias]['left'] => $counter,
  686
+						$this->settings[$Model->alias]['right'] => $counter + 1
  687
+					),
  688
+					array($Model->escapeField() => $parentId)
  689
+				);
  690
+				$counter += 2;
  691
+			}
  692
+		}
  693
+
  694
+		while ($children) {
  695
+			foreach ($children as $row) {
682 696
 				$counter = $this->_recoverByParentId($Model, $counter, $row[$Model->alias][$Model->primaryKey]);
683 697
 			}
684  
-			$params['page']++;
685  
-			if (count($rows) !== $params['limit']) {
  698
+
  699
+			if (count($children) !== $params['limit']) {
686 700
 				break;
687 701
 			}
  702
+			$params['page']++;
  703
+			$children = $Model->find('all', $params);
688 704
 		}
689 705
 
690  
-		if (!is_null($parentId)) {
  706
+		if (!is_null($parentId) && $hasChildren) {
691 707
 			$Model->updateAll(
692 708
 				array($this->settings[$Model->alias]['right'] => $counter),
693 709
 				array($Model->escapeField() => $parentId)

0 notes on commit e92e3df

Please sign in to comment.
Something went wrong with that request. Please try again.