Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add path enumerable trait #155

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from
Prev Previous commit
Next Next commit
Add getNested method and test
  • Loading branch information
bennothommo committed Aug 31, 2023
commit 62411f87c1839f4565bca3f4c0c7d0e559a7984e
8 changes: 8 additions & 0 deletions src/Database/Traits/PathEnumerable.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,14 @@ public function getAllChildren(): Collection
return $this->newQuery()->descendants()->get();
}

/**
* Gets a nested collection of all records.
*/
public function getNested(): Collection
{
return $this->newQuery()->get()->toNested();
}

/**
* Root nodes scope.
*
Expand Down
31 changes: 31 additions & 0 deletions tests/Database/Traits/PathEnumerableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,37 @@ public function testDeleteRecordWithChildren()
$this->assertNull(TestModelEnumerablePath::find($child->id));
}

public function testGetNestedRecords()
{
$grandparents = new TestModelEnumerablePath([
'name' => 'Grandparents',
]);
$parents = new TestModelEnumerablePath([
'name' => 'Parents',
]);
$daughter = new TestModelEnumerablePath([
'name' => 'Daughter',
]);
$child = new TestModelEnumerablePath([
'name' => 'Child',
]);

$grandparents->save();
$parents->parent = $grandparents;
$parents->save();
$daughter->parent = $parents;
$daughter->save();
$child->parent = $daughter;
$child->save();

$grandparents->reload();
$nested = $grandparents->getNested();
$this->assertEquals($grandparents->name, $nested->get(1)->name);
$this->assertEquals($parents->name, $nested->get(1)->children->get(0)->name);
$this->assertEquals($daughter->name, $nested->get(1)->children->get(0)->children->get(0)->name);
$this->assertEquals($child->name, $nested->get(1)->children->get(0)->children->get(0)->children->get(0)->name);
}

protected function createTable()
{
$this->getBuilder()->create('path_enumerable', function ($table) {
Expand Down
Loading