Skip to content

Commit

Permalink
Added getAncestorByLevel (#12)
Browse files Browse the repository at this point in the history
* add method getAncestorByLevel
  • Loading branch information
cugrif authored and pvsaintpe committed Oct 22, 2019
1 parent 87ded83 commit 1e23359
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Interfaces/LTreeModelInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public function getLtreeLevel(): int;
public function getLtreeProxyDeleteColumns(): array;
public function getLtreeProxyUpdateColumns(): array;
public function isParentOf(int $id): bool;
public function getAncestorByLevel(int $level = 1);

// relations
public function ltreeParent(): BelongsTo;
Expand Down
9 changes: 9 additions & 0 deletions src/Traits/LTreeModelTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,13 @@ public function renderAsLtree($value, $pad_string = LTreeHelper::PAD_STRING, $pa
{
return LTreeHelper::renderAsLTree($value, $this->getLtreeLevel(), $pad_string, $pad_type);
}

public function getAncestorByLevel(int $level = 1)
{
return static::whereRaw(sprintf(
"({$this->getLtreePathColumn()} @> text2ltree('%s')) and nlevel(path) = %d",
LTreeHelper::pathAsString($this->getLtreePath()),
$level)
)->first();
}
}
15 changes: 15 additions & 0 deletions tests/Functional/LtreeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,21 @@ public function root(): void
}
}

/** @test */
public function getAncestorByLevel(): void
{
$tree = $this->createTreeNodes($this->getTreeNodes());
$parent = $tree[1];
$descendants = $parent::descendantsOf($parent)->withoutSelf(1);
$this->assertGreaterThan(0, $descendants->count());
$descendants->each(static function ($descendant) use ($parent) {
$descendant->getAncestorByLevel($parent->id);
});

$this->assertSame($tree[5]->getAncestorByLevel(2)->id, $tree[2]->id);
$this->assertSame($tree[8]->getAncestorByLevel(3)->id, $tree[6]->id);
}

private function initLTreeService()
{
DB::statement('CREATE EXTENSION IF NOT EXISTS LTREE');
Expand Down

0 comments on commit 1e23359

Please sign in to comment.