Creating a Tree Structure within a CakePHP Model
My assumption going into this was that creating a tree-like relationship within one of my models would be fairly straightforward with Cake’s model relationships. As it turns out, I was absolutely correct.
Let’s say we want to create a model called “Category”, and each category can belong to a parent category. In other words, we want our application to recognize that every category may potentially belong to a higher-level category, and likewise, that every category may also have child categories beneath it.
Consider a Category model similar to the following:
CREATE TABLE `categories` ( `id` INTEGER(12) NOT NULL AUTO_INCREMENT, `name` VARCHAR(64) NOT NULL, `parent_id` INTEGER(12) NULL, PRIMARY KEY(`id`) );
The first step is to define our model (obviously):
<?php
class Category extends AppModel {
var $name = 'Category';
}
?>
Next, let’s tell Cake that a category can belong to other categories using the belongsTo association:
< ?php
class Category extends AppModel {
var $name = 'Category';
var $belongsTo = array(
'ParentCategory' => array(
'className' => 'Category',
'foreignKey' => 'parent_id'
));
}
?>
Finally, we want to tell Cake that a category can have other categories beneath it. We’ll do this using the hasMany association:
< ?php
class Category extends AppModel {
var $name = 'Category';
var $belongsTo = array(
'ParentCategory' => array(
'className' => 'Category',
'foreignKey' => 'parent_id'
));
var $hasMany = array(
'ChildCategory' => array(
'className' => 'Category',
'foreignKey' => 'parent_id'
));
}
?>
That’s it. Create a controller for categories and turn on scaffolding, and you’ll see how nicely this all works out.
Missing Database Table
Error: Database table parent_categories for model ParentCategory was not found.
Notice: If you want to customize this error message, create app\views\errors\missing_table.ctp
@echo: You’ve made an error in setting up your model relationships. There is no ParentCategory model; it’s simply an alias for Cake to refer to the related Category model.
Error: Database table child_areas for model ChildArea was not found.