diff --git a/src/Concerns/BelongsToOrderedTree.php b/src/Concerns/BelongsToOrderedTree.php index 5b8ce8d..9b250a0 100644 --- a/src/Concerns/BelongsToOrderedTree.php +++ b/src/Concerns/BelongsToOrderedTree.php @@ -9,6 +9,7 @@ trait BelongsToOrderedTree use BelongsToTree { children as _children; setChildrenFromDescendants as _setChildrenFromDescendants; + getTree as _getTree; } use Orderable; @@ -32,4 +33,13 @@ protected function setChildrenFromDescendants($descendants) { $this->_setChildrenFromDescendants($descendants->sortBy($this->getOrderColumn())); } + + /** + * @param int $depth + * @return \Illuminate\Database\Eloquent\Collection + */ + public static function getTree($depth = null) + { + return static::_getTree($depth)->sortBy((new static)->getOrderColumn())->values(); + } } diff --git a/tests/OrderedTreeTest.php b/tests/OrderedTreeTest.php index c11e74d..2777715 100644 --- a/tests/OrderedTreeTest.php +++ b/tests/OrderedTreeTest.php @@ -111,4 +111,22 @@ public function test_ordered_descendants() $this->assertEquals($this->items[6]->id, $items[1]->children[1]->children[0]->id); $this->assertEquals($this->items[1]->id, $items[1]->children[1]->children[1]->id); } + + public function test_tree_order() + { + // 3 0 + // 2 7 5 4 + // 6 1 + + $this->setParent([5, 4], 0); + $this->setParent([2, 7], 3); + $this->setParent([6, 1], 7); + $roots = Model::whereIsRoot()->get(); + $roots[0]->swapWith($roots[1]); + $tree = Model::getTree(); + + $this->assertEquals($this->items[3]->id, $tree[0]->id); + $this->assertEquals($this->items[2]->id, $tree[0]->children[0]->id); + $this->assertEquals($this->items[6]->id, $tree[0]->children[1]->children[0]->id); + } }