I have a table called categories. The table holds categories and their sub(subsub)categories...
Its an easy table:
This way I can make categories with endless depth... I kinda hoped that cakephp would understand parent_id (I also tried category_id, but that makes cakePHP join on itself :D )
What is the right way to tackle this?
NOTE: There is also a 'many to many' table called places. Those places can belong to one or more categories.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With