Browse Source

Optimizing some queries in the TreeBehavior

Jose Lorenzo Rodriguez 12 years ago
parent
commit
825b830ba3

+ 11 - 4
src/Model/Behavior/TreeBehavior.php

@@ -156,8 +156,7 @@ class TreeBehavior extends Behavior {
 		$this->_sync($diff, '+', "BETWEEN {$min} AND {$max}");
 
 		if ($right - $left > 1) {
-			//Inverting sign again
-			$this->_sync('-1', '*', "< 0");
+			$this->_unmarkInternalTree();
 		}
 
 		//Allocating new position
@@ -182,14 +181,22 @@ class TreeBehavior extends Behavior {
 		$this->_sync($diff + 1, '-', "BETWEEN {$right} AND {$edge}");
 
 		if ($right - $left > 1) {
-			//Inverting sign again
-			$this->_sync('-1', '*', "< 0");
+			$this->_unmarkInternalTree();
 		}
 
 		$entity->set($config['left'], $edge - $diff);
 		$entity->set($config['right'], $edge);
 	}
 
+	protected function _unmarkInternalTree() {
+		$config = $this->config();
+		$query = $this->_table->query();
+		$this->_table->updateAll([
+			$query->newExpr()->add("{$config['left']} = {$config['left']} * -1"),
+			$query->newExpr()->add("{$config['right']} = {$config['right']} * -1"),
+		], [$config['left'] . ' <' => 0]);
+	}
+
 	public function findPath($query, $options) {
 		if (empty($options['for'])) {
 			throw new \InvalidArgumentException("The 'for' key is required for find('path')");

+ 2 - 2
tests/TestCase/Model/Behavior/TreeBehaviorTest.php

@@ -321,7 +321,7 @@ class TreeBehaviorTest extends TestCase {
 
 		$expected[] = $entity->toArray();
 		$results = $table->find()->order('lft')->hydrate(false)->toArray();
-		$this->assertEquals($expected, $result);
+		$this->assertEquals($expected, $results);
 	}
 
 /**
@@ -362,7 +362,7 @@ class TreeBehaviorTest extends TestCase {
 		$this->assertEquals(9, $entity->lft);
 		$this->assertEquals(10, $entity->rght);
 
-		$result = $table->find()->order('lft')->hydrate(false)->toArray();
+		$results = $table->find()->order('lft')->hydrate(false)->toArray();
 		$table->recover();
 		$expected = $table->find()->order('lft')->hydrate(false)->toArray();
 		$this->assertEquals($expected, $results);