CakePHP tree behaviour not working (what I am doing wrong?)

I am learning cakePHP 3 and trying to store hierarchical data in a table. I have added parent_id, lft and rght columns. Added $this->addBehavior(‘Tree’) in initialize method for this table. Calling recover method.

So seems all is done as described here: https://book.cakephp.org/3.0/en/orm/behaviors/tree.html But no one child row is returned.

That is interesting, that childCount returns -0.5 for each row (no matter if the row has children or not, always -0.5).

I am newbie in cakePHP, so maybe someone can help, what I am doing wrong?

Without code, nobody can see what you’re doing wrong :slight_smile:

1 Like

This is my categories model:
<?php

namespace App\Model\Table;

use Cake\ORM\Table;

class CategoriesTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior(‘Tree’);
}
}

And this is categories controller (beginning):
public function categories(){
$categories = TableRegistry::get(‘Categories’);
$categories->recover();

$children = $categories
->find(‘children’, [‘for’ => 203])
->find(‘threaded’)
->toArray();

foreach ($children as $child) {
echo “blablabla”;
}

Categories table:
CREATE TABLE categories (
categoryID int(11) NOT NULL,
categoryTitle varchar(255) NOT NULL DEFAULT ‘’,
parent_id int(11) NOT NULL DEFAULT ‘0’,
categoryPosition int(11) NOT NULL DEFAULT ‘10’,
categoryURL varchar(255) DEFAULT NULL,
categoryHeaderText varchar(255) NOT NULL,
categoryPageTitle varchar(255) NOT NULL,
categoryPageDescription varchar(255) NOT NULL,
categoryMetaTags varchar(255) NOT NULL,
categoryIsDefaultForDomain int(11) NOT NULL,
lft int(11) NOT NULL,
rght int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

I suppose that recover() is not working for some reason. Because every row has 0 in lft and rght columns

I have checked it, when I manually added lft and rght - everything is Ok.
Does anybody know why recover may fail? I could add all lfts and rghts manually, but it is a bad decision, and my table has too many rows:)

Just double checking; the categories table contains 2 layers of data already?

sorry what you mean? I have manually created lft and rght and it is working now. But auto generating is now working

Yes, that is what I meant; one root, one left, one right.
So if foreach ($children as $child) returns nothing, the array must be empty. What happens if you remove “->toArray()” then use debug() to put the result of “$children” on the screen?