0

How to find all the ancestors (not only direct parent) of a record with the following model:

class Model_Category extends ORM {

protected $_belongs_to = array(
        'parent' => array('model' => 'Category', 'foreign_key' => 'category_id'),
);

protected $_has_many = array(
        'children' => array('model' => 'Category', 'foreign_key' => 'category_id'),
);

$category->parent->find() is only giving the direct parent and even when trying to fetch the parent of the parent with a recursive function it throws Kohana_Exception: Method find() cannot be called on loaded objects.

This occurs so natural to me that I guess there must an easy way to do it - I'm not sure if it's me or the lack of documentation on ORM relations - halp!

Petrunov
  • 754
  • 1
  • 8
  • 18

3 Answers3

1

You should be able to do this with a recursive function or a while loop

$current = $category;
while ($current->parent->loaded())
{
    //save $current
    $current = $category->parent;
}
kero
  • 10,647
  • 5
  • 41
  • 51
1

Use Nested Sets. For example, https://github.com/evopix/orm-mptt. It has special methods like parents(), children(), siblings() etc. Of course, this requires modifications in your DB table.

biakaveron
  • 5,493
  • 1
  • 16
  • 20
0

Ok, turns out the related models actually ARE included, cause if you do

$category->parent->parent->name it will be the name of the grand-parent of $category.

My problem was that I was printing $category->parent->as_array() and expecting to see the parent relations in the (multidimensional) array which simply appears not to be the case with kohana.

Petrunov
  • 754
  • 1
  • 8
  • 18