How to implement a self referencing (parent_id) model in cakephp
Tree behaviour is overkill for this situation. You just need to set your model up like this:
class Category extends AppModel {
public $hasMany = array(
'Children'=>array(
'className'=>'Category',
'foreignKey'=>'parent_id'
)
);
public $belongsTo = array(
'Parent'=>array(
'className'=>'Category',
'foreignKey'=>'parent_id'
)
);
}
Now, when you do a find() on Category, you'll get two additional Models called Parent (which points to the parent id) and Children (which lists it's children).
Look at the tree behaviour; with MPTT logic. The link supplied to Oracle's website is dead; but you can find a bunch of material about how to use it on the cake manual and online.
CREATE TABLE categories (
id INTEGER(10) UNSIGNED NOT NULL AUTO_INCREMENT,
parent_id INTEGER(10) DEFAULT NULL,
lft INTEGER(10) DEFAULT NULL,
rght INTEGER(10) DEFAULT NULL,
name VARCHAR(255) DEFAULT '',
PRIMARY KEY (id)
);
Just make sure your table matches that structure for best results within Cake and it's baking.
In Category model: belongsTo Parent and hasMany Children, both have the class 'Category' and foreign key 'parent_id'