sradha sradha - 3 months ago 38
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(['Menus.id DESC'])->toArray();


This is the controller code.

enter image description here

Thank you.

Answer

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])
    ->contain('SubMenus')
    ->order(['Menus.id DESC'])
    ->toArray();
Comments