Creating menu with tree behavior

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

I can only advise you to use the Tree Behaviour. This also gives you the possibility to handle more than 2 menulevels :slight_smile:

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:

It is called Modified Preorderd Tree Traversal or MPTT. Sitepoint has a good overview on how it works at the schema/DB level.

its called “nested sets”

You can use the TreeHelper available in to easily generate menus for models using TreeBehavior or nested dataset fetched using find('threaded').