Erik Wiesenthal Wed Sep 14 11:20:14 -0400 2011

Subject: Tree Object

Hi all,

I'm triying to create a Tree using a Db Model, lets the code talks


class Content extends ActiveRecord\Model {

    static $table_name  = 'content';
    static $primary_key = 'pk';

    static $has_many = array(
        array('childrens', 'class_name' => 'Content', 'foreign_key'=>'parent_fk')
    );

    static $belongs_to = array(
        array('parent', 'class_name' => 'Content', 'foreign_key'=>'parent_fk'),
    );      

    static function tree($parent, $depth = 0){

        $options = array(
            'conditions'=>array('parent_fk'=>array($parent))   // 'include'=>array('childrens')
        );

        $results = self::find('all', $options);

        if($depth > 0){
            foreach($results as $key=>$result){
                $results[$key]->childrens = self::tree($result->pk, $depth--);
            }     

        } 
        return $results;
    }
} 

my problem here is that ->childrens is not defined and if I defined it as a public var on the object it overload, in some way my "childrens" have-many association.

I wonder if there is a way to get the tree in this way, using the "childrens" property, or maybe i must create another object property for the tree childrens (wich will be sad) :D
Thanks in advanced
(please forget my english)


Clay vanSchalkwijk Wed Sep 14 19:37:59 -0400 2011

The relationship is already recursive, so you don't need to query it again in your tree. Could you explain what it is you are trying to do?

Erik Wiesenthal Thu Sep 15 03:59:46 -0400 2011

Ouch, sorry for it,

When you say is already recursive, you mean i can call it with some param to return recursive results?

I want my tree method to return all "content" wich parent_fk as defined, and all its childrens, and childrens of the childrens..., until "depth" is reached.

It does not work because i need to define a new "public var $childrens" for the one in the tree method. If i do it, the "childrens" relationship does not work anymore.
The unique solution i found is to change the name of the Relationship, or the one at the tree function "childrens". Both can't be "childrens". For me it is a shame since they are the same.

(1-2/2)