I have a table with a parent_id, i am trying to build a menu system, that chains with a recursive function
id | parent_id | title | url
1 0 home
2 1 about
3 2
cake console generated
//Menus Table
public function initialize(array $config){
$this->belongsTo('ParentMenus', [
'className' => 'Menus',
'foreignKey' => 'parent_id'
]);
$this->hasMany('ChildMenus', [
'className' => 'Menus',
'foreignKey' => 'parent_id'
]);
public function buildRules(RulesChecker $rules){
$rules->add($rules->existsIn(['parent_id'], 'ParentMenus'));
return $rules;
}
Which works great but the top menu item I give it a parent _id of 0 which doesn’t save because it doesn’t exist. Is there a way i can allow 0? I am creating button controls to allow being able to move up and down and rearrange the menu
mo86
May 4, 2016, 9:32pm
2
I can only advise you to use the Tree Behaviour. This also gives you the possibility to handle more than 2 menulevels
http://book.cakephp.org/3.0/en/orm/behaviors/tree.html
thank you i didnt know cake had something built in i will look into it
do u know what this concept is called outside of cake parent_id lft right so i can read up, i learn this in college but forgot
Its called trees.
another workaround that i used in the past is to set parent_id to NULL when is a top menu. It should work with cake
i did that NULL as parent but i ran into another issue i couldnt do a query find parent ID equal to NULL it returned nothing
also another question this tree system what dors lft and right represent? the nodes above and below them? and if yes if its under the parent item does that mean left is NULL or the parent id and left are the same
hopefully that makes sense thank you
You need to pass IS … like this
$query->where(["parent_id IS" => null]);
And lft and rgt are the left and rigth node (All nodes sharing the same parent_id can be ordered using that columns)
Specifically, the algorithm is called MPTT (Modified Preorder Tree Traversal). There’s a good article explaining how it works here: http://www.sitepoint.com/hierarchical-data-database-2/
It is called Modified Preorderd Tree Traversal or MPTT. Sitepoint has a good overview on how it works at the schema/DB level.
ADmad
May 14, 2016, 8:23am
11
You can use the TreeHelper
available in https://github.com/ADmad/cakephp-tree to easily generate menus for models using TreeBehavior
or nested dataset fetched using find('threaded')
.