PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, January 11, 2022

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

 January 11, 2022     cakephp, database-design     No comments   

Issue

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.


Solution

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



Answered By - RichardAtHome
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing