How to link two tables so that I can get the main nodes and their child nodes with find threaded?
My target is to render a menu like this
<ul>
<li class="category">Category 1</li>
<ul>
<li class="sub">Subcategory 1</li>
...
</ul>
<li class="category">Category 2</li>
<ul>
<li class="sub">Subcategory 1</li>
...
</ul>
</li>
</ul>
I have created two tables.
Categories
CREATE TABLE `categories` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `categories` (`id`, `name`) VALUES (NULL, 'Category 1');
INSERT INTO `categories` (`id`, `name`) VALUES (NULL, 'Category 2');
Subcategories
CREATE TABLE `subcategories` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`category_id` INT UNSIGNED NULL DEFAULT NULL
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `subcategories` (`id`, `name`, `category_id`) VALUES (NULL, 'Subcategory 1', 1);
INSERT INTO `subcategories` (`id`, `name`, `category_id`) VALUES (NULL, 'Subcategory 1', 1);
INSERT INTO `subcategories` (`id`, `name`, `category_id`) VALUES (NULL, 'Subcategory 1', 1);
INSERT INTO `subcategories` (`id`, `name`, `category_id`) VALUES (NULL, 'Subcategory 1', 2);
INSERT INTO `subcategories` (`id`, `name`, `category_id`) VALUES (NULL, 'Subcategory 1', 2);
My association for these two tables look like
class CategoriesTable extends Table
{
public function initialize(array $config)
{
$this->belongsTo('Subcategories', [
'foreignKey' => 'category_id'
]);
}
...
}
class SubcategoriesTable extends Table
{
public function initialize(array $config)
{
$this->belongsTo('Categories');
}
...
}
When i now output the Result of
TableRegistry::getTableLocator()->get('Categories')->find('threaded')->toArray();
I get the list of Categories but the children nodes are empty as of missing of parent_id.
According to the definition of CakePHP you should use a parent_id for this. But I am not clear how to use this.
https://book.cakephp.org/3/en/orm/retrieving-data-and-resultsets.html#finding-threaded-data
I am still CakePHP beginner and maybe somebody can help me with this.