0

let's say that I have a table called categories which is using the Tree Behavior in a CakePHP 3 application. If I'm given a Category id, are there functions that allow me to check if the Category is a parent Category or fuctions to get the parent Category of a node without having to do multiple find queries?

I couldn't find anything on the web.

Thanks for any help

user765368
  • 19,590
  • 27
  • 96
  • 167

2 Answers2

1

TreeBehavior use parent_id field, so You can prepare relations named ParentCategories and ChildrenCategories.

$this->belongsTo('ParentCategories', [
    'className' => 'Categories',
    'foreignKey' => 'parent_id',
]);

$this->hasMany('ChildrenCategories', [
    'className' => 'Categories',
    'foreignKey' => 'parent_id',
]);
kicaj
  • 2,881
  • 5
  • 42
  • 68
0

According to Cakephp 3

there is already a Path finder available to find the complete path for a specific node/id. Using this you can get the parent node as below:

$completePath = $this->Model->find('path', ['for' => $category_id])->first();
$parentNode = $completePath['id']; 

Further reference: https://github.com/cakephp/cakephp/issues/12539

Hope this will help!

Sehdev
  • 5,486
  • 3
  • 11
  • 34