Search code examples
phprecursionyiihierarchy

Get category tree recursively (Yii)


I have a table with following structure:

categories

  • id
  • name
  • parent_id

I want to get the tree of categories with single function. I've written something like this in my model, but it doesn't work.

public function getChildren($parent) { 
        $criteria = new CDbCriteria;
        $criteria->condition='parent_id=:id';
        $criteria->params=array(':id'=>$parent);
        $model = Term::model()->findAll($criteria);
        while ($model) {
            echo $model->id . "<br />";
            $this->getChildren;
        }
}

Can someone help me with this? Thanks.


Solution

  • I've finally solved the issue. If someone interested, here's the code:

    public function getChildren($parent, $level=0) { 
            $criteria = new CDbCriteria;
            $criteria->condition='parent_id=:id';
            $criteria->params=array(':id'=>$parent);
            $model = $this->findAll($criteria);
            foreach ($model as $key) {
                echo str_repeat(' — ', $level) . $key->name . "<br />";
                $this->getChildren($key->id, $level+1);
            }
        }
    public function getChildrenString($parent) { 
            $criteria = new CDbCriteria;
            $criteria->condition='parent_id=:id';
            $criteria->params=array(':id'=>$parent);
            $model = $this->findAll($criteria);
            foreach ($model as $key) {
                $storage .= $key->id . ","; 
                $storage .= $this->getChildrenString($key->id);
            }
            return $storage;
        }