Skip to content

Instantly share code, notes, and snippets.

@rela589n
Created December 7, 2023 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rela589n/8d340226a93a4585d01e8df8c513f405 to your computer and use it in GitHub Desktop.
Save rela589n/8d340226a93a4585d01e8df8c513f405 to your computer and use it in GitHub Desktop.
postgresql dfs preorder tree traversal
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