Skip to content

Commit

Permalink
Merge pull request #12 from PascalThesing/add-select-node-and-children
Browse files Browse the repository at this point in the history
Add select for node and his children
  • Loading branch information
JanPietrzyk authored May 9, 2018
2 parents ddb83c7 + 076a179 commit e63f5c8
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,4 @@ export DB_PASSWORD='bar'
export DB_HOST='baz'

bin/phpunit
```
```
31 changes: 31 additions & 0 deletions src/NestedSetQueryFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,37 @@ public function createChildrenQueryBuilder(
->setParameter("{$queryAlias}Root", $nodeData['root_id']);
}

/**
* Select a parent and all it's children
*
* @param string $tableExpression
* @param string $queryAlias
* @param string $rootColumnName
* @param int $parentId
* @return QueryBuilder
*/
public function createParentAndChildrenQueryBuilder(
string $tableExpression,
string $queryAlias,
string $rootColumnName,
int $parentId
): QueryBuilder {
$this->setRootColName($rootColumnName, $this->connection);
$nodeData = $this->reader->fetchNodeData($tableExpression, $rootColumnName, $parentId);

return $this->connection->createQueryBuilder()
->from($this->connection->quoteIdentifier($tableExpression), $queryAlias)
->where("{$queryAlias}.{$this->levelCol} >= :{$queryAlias}Level")
->andWhere("{$queryAlias}.{$this->leftCol} >= :{$queryAlias}Left")
->andWhere("{$queryAlias}.{$this->leftCol} <= :{$queryAlias}Right")
->andWhere("{$queryAlias}.{$this->rootCol} = :{$queryAlias}Root")
->orderBy("{$queryAlias}.{$this->leftCol}")
->setParameter("{$queryAlias}Level", $nodeData['level'])
->setParameter("{$queryAlias}Left", $nodeData['left'])
->setParameter("{$queryAlias}Right", $nodeData['right'])
->setParameter("{$queryAlias}Root", $nodeData['root_id']);
}

/**
* Get the subtree relative to a single node
*
Expand Down
16 changes: 16 additions & 0 deletions tests/NestedSetQueryFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,22 @@ public function test_fetch_all_children()
$this->assertEquals('Suits', $rows[0]['name']);
}

public function test_fetch_all_children_and_node()
{
$qb = $this->queryFactory->createParentAndChildrenQueryBuilder('tree', 't', 'root_id', 24)
->select('*');

$sql = $qb->getSQL();

$this->assertContains('tree', $sql);
$this->assertContains('t.', $sql);

$rows = $qb->execute()->fetchAll();

$this->assertCount(3, $rows);
$this->assertEquals('Suits', $rows[0]['name']);
}

public function test_fetch_subtree()
{
$qb = $this->queryFactory->createSubtreeQueryBuilder('tree', 't', 'root_id', 2)
Expand Down

0 comments on commit e63f5c8

Please sign in to comment.