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

后端 未结 6 1051
悲&欢浪女
悲&欢浪女 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 07:01

    RichardAtHome's answer is the right one. In CakePHP 3.+ you write:

         $this->hasMany('Children', [
                'className'=>'Category',
                'foreignKey'=>'parent_id'
         ]);
    
        $this->belongsTo('Parent', [
            'className'=>'Category',
            'foreignKey'=>'parent_id'
        ]);
    

    and don't forger to use 'contain' in your 'find', e.g.:

            $categories = $this->find("all")
               ->order(...)
               ->contain(['Children']);
    

提交回复
热议问题