sradha sradha - 1 year ago 152
PHP Question

Model association on same table (for menu and submenu concept) in cakephp 3.2

I have tried a lot for the model association in cake 3. There is one table menu,it consists of both the menu and sub menu .Here i want to bind parent menu with its child menu , but i have not yet succeeded to grab it.

Below i have written the code as well as attached a screenshot,
Thank you .

$this->hasMany('Menus', [
'className' => 'Menus',
'foreignKey' => 'parent_id',


This is the bind in Menus model

$getListOfAllParentMenus = $this->Menus->find('all')->where(['Menus.parent_id' => 0])->contain('Menus')->order([' DESC'])->toArray();

This is the controller code.

enter image description here

Thank you.

Answer Source

You should change the name of the associated model since you can't contain on the same model. Change Menus to SubMenus.

$this->hasMany('SubMenus', [
     'className' => 'Menus',
     'foreignKey' => 'parent_id',

$getListOfAllParentMenus = $this->Menus->find('all')
    ->where(['Menus.parent_id' => 0])
    ->order([' DESC'])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download