diff --git a/NestedSetsBehavior.php b/NestedSetsBehavior.php index 5241952..963a462 100644 --- a/NestedSetsBehavior.php +++ b/NestedSetsBehavior.php @@ -228,14 +228,13 @@ class NestedSetsBehavior extends Behavior $key = $this->owner->getAttribute($this->leftAttribute); $relates = []; - $relates[$key] = []; $parents = [$key]; $prev = $this->owner->getAttribute($this->depthAttribute); foreach($nodes as $node) { - $depth = $node->getAttribute($this->depthAttribute); - if ($depth <= $prev) { - $parents = array_slice($parents, 0, $depth - $prev - 1); + $level = $node->getAttribute($this->depthAttribute); + if ($level <= $prev) { + $parents = array_slice($parents, 0, $level - $prev - 1); } $key = end($parents); @@ -245,14 +244,17 @@ class NestedSetsBehavior extends Behavior $relates[$key][] = $node; $parents[] = $node->getAttribute($this->leftAttribute); - $prev = $depth; + $prev = $level; } + $ownerDepth = $this->owner->getAttribute($this->depthAttribute); $nodes[] = $this->owner; foreach ($nodes as $node) { $key = $node->getAttribute($this->leftAttribute); if (isset($relates[$key])) { $node->populateRelation('children', $relates[$key]); + } elseif ($depth === null || $ownerDepth + $depth > $node->getAttribute($this->depthAttribute)) { + $node->populateRelation('children', []); } } diff --git a/tests/NestedSetsBehaviorTestCase.php b/tests/NestedSetsBehaviorTestCase.php index 4033b0f..fd2c000 100644 --- a/tests/NestedSetsBehaviorTestCase.php +++ b/tests/NestedSetsBehaviorTestCase.php @@ -136,6 +136,14 @@ class NestedSetsBehaviorTestCase extends BaseTestCase $node = Node::findOne(19); $node->populateTree(1); $this->assertEquals(true, $node->isRelationPopulated('children')); + + $node = Node::findOne(1); + $node->populateTree(1); + $this->assertEquals(false, $node->children[1]->isRelationPopulated('children')); + + $node = Node::findOne(1); + $node->populateTree(2); + $this->assertEquals(true, $node->children[1]->isRelationPopulated('children')); } public function testIsRoot()