Created
December 7, 2023 09:05
-
-
Save rela589n/8d340226a93a4585d01e8df8c513f405 to your computer and use it in GitHub Desktop.
postgresql dfs preorder tree traversal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function findCategories(): array | |
{ | |
// dfs preorder tree traversal | |
$sql = <<<'SQL' | |
WITH RECURSIVE preorder_categories_traversal | |
AS (SELECT category.id, | |
category.parent_id, | |
ARRAY [ROW (category.sort_order,category.id)] AS path | |
FROM categories category | |
WHERE category.parent_id IS NULL | |
UNION ALL | |
SELECT category.id, | |
category.parent_id, | |
preorder_categories_traversal.path || ROW (category.sort_order,category.id) AS path | |
FROM preorder_categories_traversal | |
INNER JOIN categories category | |
ON preorder_categories_traversal.id = category.parent_id) | |
SELECT category.* | |
FROM categories category | |
INNER JOIN preorder_categories_traversal tree ON category.id = tree.id | |
WHERE category.template_id = :template_id | |
ORDER BY tree.path ASC; | |
SQL; | |
$query = $this | |
->getEntityManager() | |
->createNativeQuery($sql, $this->buildRsm()) | |
->setParameter('template_id', 123); | |
/** @var SurveyTemplateSection[] $results */ | |
$results = $query->execute(); | |
return $results; | |
} | |
private function buildRsm(): ResultSetMappingBuilder | |
{ | |
$rsm = new ResultSetMappingBuilder($this->getEntityManager()); | |
$rsm->addRootEntityFromClassMetadata(Category::class, 'category'); | |
return $rsm; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment