Object relational mapping - Hierarchical data - Introduction - Traversing or Walking Trees.php 1.26 KB
Newer Older
1

hansbrix's avatar
hansbrix committed
2 3 4 5 6

You can traverse a Tree in different ways, please see here for more information [http://en.wikipedia.org/wiki/Tree_traversal http://en.wikipedia.org/wiki/Tree_traversal].



7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
The most common way of traversing a tree is Pre Order Traversal as explained in the link above, this is also what is known as walking the tree, this is the default approach when traversing a tree in Doctrine, however Doctrine does plan to provide support for Post and Level Order Traversal (not currently implemented)



<code type="php">
/*
 * traverse the entire tree from root
 */
$root = $manager->getTable('Model')->getTree()->fetchRoot();
if($root->exists())
{
	$tree = $root->traverse();
	while($node = $tree->next())
	{
		// output your tree here
	}
}

// or the optimised approach using tree::fetchTree
$tree = $manager->getTable('Model')->getTree()->fetchTree();
while($node = $tree->next())
{
	// output tree here
}

/*
 * traverse a branch of the tree
 */
$record = $manager->getTable('Model')->find($pk);
if($record->exists())
{
	$branch = $record->traverse();
	while($node = $branch->next())
	{
		// output your tree here
	}
}

// or the optimised approach
$branch = $manager->getTable('Model')->getTree()->fetchBranch($pk);
while($node = $branch->traverse())
{
	// output your tree here
}

</code>