How do I model a tree/hierarchy?
From PHP on Trax
Tree structures or hierarchies are simple to design in PoT. Simply add the parent_id column to the table and use something like this in your model:
<?
class Category extends ActiveRecord {
public $belongs_to = array( "parent" => array(
"class_name" => "Category")
);
public $has_many = array( "children" => array(
"foreign_key" => "parent_id",
"class_name" => "Category")
);
}
?>
In the controller we only load entries that have a parent_id of 0 (root elements):
<?
class CategoryController extends ApplicationController {
function tree() {
$category = new Category();
$this->categories = $category->find_all("parent_id=0");
}
}
?>
And finally we could use a function like this to show a structured list of the tree:
<?php
function cattree($items) {
$r = "";
if (count($items) && is_array($items)) {
$r .= "<ul>\n";
foreach ($items as $item) {
$r .= '<li>' . $item->title . ' [' . $item->id . '|' . $item->parent_id . ']';
if (count($item->children)) {
$r .= cattree($item->children);
}
$r .= "</li>\n";
}
$r .= "</ul>\n";
}
return $r;
}
?>
<?= cattree($categories); ?>
- Category 1 [1|0]
- Category 4 [4|1]
- Category 5 [5|1]
- Category 7 [7|5]
- Category 2 [2|0]
- Category 6 [6|2]
- Category 3 [3|0]
