Browse Source

Making adding new node as a descendat of a root work

Jose Lorenzo Rodriguez 12 years ago
parent
commit
ca226c9ba6

+ 5 - 3
src/Model/Behavior/TreeBehavior.php

@@ -86,7 +86,7 @@ class TreeBehavior extends Behavior {
 			$edge = $parentNode->get($config['right']);
 			$entity->set($config['left'], $edge);
 			$entity->set($config['right'], $edge + 1);
-			$this->_sync(2, '+', ">= {$config['right']}");
+			$this->_sync(2, '+', ">= {$edge}");
 		}
 
 		if ($isNew && !$parent) {
@@ -102,9 +102,11 @@ class TreeBehavior extends Behavior {
 
 	protected function _getParent($id) {
 		$config = $this->config();
+		$primaryKey = (array)$this->_table->primaryKey();
 		$parentNode = $this->_scope($this->_table->find())
-			->select([$config['lft'], $config['rght']])
-			->where([$primaryKey[0] => $parent]);
+			->select([$config['left'], $config['right']])
+			->where([$primaryKey[0] => $id])
+			->first();
 
 		if (!$parentNode) {
 			throw new \Cake\ORM\Error\RecordNotFoundException(

+ 23 - 0
tests/TestCase/Model/Behavior/TreeBehaviorTest.php

@@ -324,4 +324,27 @@ class TreeBehaviorTest extends TestCase {
 		$this->assertEquals($expected, $results);
 	}
 
+/**
+ * Tests that adding a child node as a decendant of one of the roots works
+ *
+ * @return void
+ */
+	public function testAddMiddle() {
+		$table = TableRegistry::get('NumberTrees');
+		$table->addBehavior('Tree');
+		$entity = new Entity(
+			['name' => 'laptops', 'parent_id' => 1],
+			['markNew' => true]
+		);
+		$this->assertSame($entity, $table->save($entity));
+		$results = $table->find()->order('lft')->hydrate(false)->toArray();
+		$this->assertEquals(20, $entity->lft);
+		$this->assertEquals(21, $entity->rght);
+
+		$expected = $table->find()->order('lft')->hydrate(false)->toArray();
+		$table->recover();
+		$result = $table->find()->order('lft')->hydrate(false)->toArray();
+		$this->assertEquals($expected, $results);
+	}
+
 }