Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a self referencing (parent_id) model in cakephp

I have a table called categories. The table holds categories and their sub(subsub)categories...

Its an easy table:

  • id
  • parent_id
  • title

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.

like image 200
Hans Wassink Avatar asked Nov 09 '11 20:11

Hans Wassink


3 Answers

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).

like image 172
RichardAtHome Avatar answered Sep 28 '22 11:09

RichardAtHome


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.

like image 44
Ross Avatar answered Sep 28 '22 11:09

Ross


In Category model: belongsTo Parent and hasMany Children, both have the class 'Category' and foreign key 'parent_id'

like image 35
Anh Pham Avatar answered Sep 28 '22 11:09

Anh Pham