Parent-child associations using the "Nested Set Model"

The "Nested Set Model" is a method for organizing records in a tree like manner. It use two columns to model the containment. Each record is given a left and a right value. It is faster in read mode than the commonly used "Adjacency List Model" which make use of a parent primary key value.

This functionnality introduce new methods to the records who defined the key "hierarchical" in their "meta_field" property array. Each of those methods may be call in 2 different ways. Either though the "hierarchy" property of the record which return a "PorteHierarchy" object or by using a shortcut which skip this property.

Simple Exemple

Command: "php samples/associations/parent-child/simple-exemple.php"


class File extends PorteRecord{
  public $meta_table = array(
    'hierarchical' => true
  );
  public $meta_fields = array(
    'title' => array()
  );
}

$parent = new File();
$parent->setTitle('Root file');
$child1 = new File();
$child1->setTitle('Child 1');
$parent->addChild($child1);
$child2 = new File();
$child2->setTitle('Child 2');
$parent->addChild($child2);
$child1OfChild1 = new File();
$child1OfChild1->setTitle('Child 1 of child 1');
$child1->addChild($child1OfChild1);
$child2OfChild1 = new File();
$child2OfChild1->setTitle('Child 2 of child 1');
$child1->addChild($child2OfChild1);

$parent->tableUpdate(array('drop'=>true));
$parent->save();

$children = $parent->getChildren();
echo '+ '.$parent->getPrimaryKey();
echo ' - '.$parent->getTitle();
echo "\r\n";
while(count($children)){
  $child = array_shift($children);
  echo '  + '.$child->getPrimaryKey();
  echo ' - '.$child->getTitle();
  $count = $child->countChildren();
  echo ' --> '.(($count>0)?$count.' children':'no child');
  echo "\r\n";
}

// + 1 - Root file
//   + 2 - Child 1 --> 2 children
//   + 5 - Child 2 --> no child
    

Available methods

The nested set model introduce the following methods:

Method "getParent"

Method "getChildren"

Method "getRootline"

Method "isRoot"

Method "getRoot"

Method "addChild"

Method "setParent"

Method "countChildren"

Method "deleteChildren"

Open Source Object Relational Mapping in PHP

Download Porte 0.2.1