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

后端 未结 6 1068
悲&欢浪女
悲&欢浪女 2021-02-06 06:35

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

Its an easy table:

  • id
  • parent_id
  • title
6条回答
  •  礼貌的吻别
    2021-02-06 06:49

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

提交回复
热议问题