Skip to content

Commit

Permalink
Issue #1: ordered tree roots should be ordered
Browse files Browse the repository at this point in the history
  • Loading branch information
Michaël committed Mar 31, 2024
1 parent 1933417 commit 8ab86be
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Concerns/BelongsToOrderedTree.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ trait BelongsToOrderedTree
use BelongsToTree {
children as _children;
setChildrenFromDescendants as _setChildrenFromDescendants;
getTree as _getTree;
}
use Orderable;

Expand All @@ -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 $this->_getTree($depth)->sortBy($this->getOrderColumn());
}
}
18 changes: 18 additions & 0 deletions tests/OrderedTreeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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($tree[0]->id, $thhis->items[3]->id);
$this->assertEquals($tree[0]->children[0]->id, $thhis->items[2]->id);
$this->assertEquals($tree[1]->children[1]->children[0]->id, $this->items[6]->id);
}
}

0 comments on commit 8ab86be

Please sign in to comment.