10.04.2018 Views

Doctrine_manual-1-2-en

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 18: Hierarchical Data 278<br />

of a root node and so on. By reading the level field from your nodes you can easily display<br />

your tree with proper ind<strong>en</strong>tion.<br />

You must never assign values to lft, rgt, level. These are managed transpar<strong>en</strong>tly by the<br />

nested set implem<strong>en</strong>tation.<br />

Multiple Trees<br />

The nested set implem<strong>en</strong>tation can be configured to allow your table to have multiple root<br />

nodes, and therefore multiple trees within the same table.<br />

The example below shows how to setup and use multiple roots with the Category model:<br />

Listing<br />

18-3<br />

// models/Category.php<br />

class Category ext<strong>en</strong>ds <strong>Doctrine</strong>_Record<br />

{<br />

// ...<br />

}<br />

public function setUp()<br />

{<br />

$options = array(<br />

'hasManyRoots' => true,<br />

'rootColumnName' => 'root_id'<br />

);<br />

$this->actAs('NestedSet', $options);<br />

}<br />

Here is the same example in YAML format. You can read more about YAML in the YAML<br />

Schema Files (page 195) chapter:<br />

Listing<br />

18-4<br />

---<br />

# schema.yml<br />

# ...<br />

Category:<br />

actAs:<br />

NestedSet:<br />

hasManyRoots: true<br />

rootColumnName: root_id<br />

columns:<br />

name: string(255)<br />

The rootColumnName is the column used to differ<strong>en</strong>tiate betwe<strong>en</strong> trees. Wh<strong>en</strong> you create a<br />

new root node you have the option to set the root_id <strong>manual</strong>ly, otherwise <strong>Doctrine</strong> will<br />

assign a value for you.<br />

In g<strong>en</strong>eral use you do not need to deal with the root_id directly. For example, wh<strong>en</strong> you<br />

insert a new node into an existing tree or move a node betwe<strong>en</strong> trees <strong>Doctrine</strong> transpar<strong>en</strong>tly<br />

handles the associated root_id changes for you.<br />

Working with Trees<br />

After you successfully set up your model as a nested set you can start working with it.<br />

Working with <strong>Doctrine</strong>'s nested set implem<strong>en</strong>tation is all about two classes:<br />

<strong>Doctrine</strong>_Tree_NestedSet and <strong>Doctrine</strong>_Node_NestedSet. These are nested set<br />

----------------- Brought to you by

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!