Categorias Com Parent_Id

Estou tentando montar uma tabela de ‘Categorias’ com a seguinte estrutura:

CREATE TABLE IF NOT EXISTS categoria (

IDCategoria int(11) NOT NULL AUTO_INCREMENT,

nome varchar(255) NOT NULL,

descricao text NOT NULL,

parent_id int(11) NOT NULL,

top int(11) NOT NULL,

ordem int(11) DEFAULT ‘0’,

status int(11) NOT NULL,

PRIMARY KEY (IDCategoria)

) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

  • na model:

    public function relations()

    {

      // NOTE: you may need to adjust the relation name and the related
    
    
      // class name for the relations automatically generated below.
    
    
      return array(
    
    
      	'categoria_parent' => array(self::BELONGS_TO, 'Categoria', 'parent_id', 'condition' => 'parent_id <> 0'), //the column in 'parent' containing 'this' id
    
    
          'categoria_childs' => array(self::HAS_MANY, 'Categoria', 'parent_id'),
    
    
      );
    

    }

  • Na minha view ADMIN da model ‘Categorias’ tenho isso:

<?php $this->widget(‘zii.widgets.grid.CGridView’, array(

'id'=&gt;'categoria-grid',


'dataProvider'=&gt;&#036;model-&gt;search(),


'filter'=&gt;&#036;model,


'columns'=&gt;array(


	'IDCategoria',


	'parent_id',


	'status',


	'nome',


	array(


		'name'=&gt;'nome',


		//'header'=&gt;'Setor',


		'value'=&gt;'&#036;data-&gt;parent_id &gt; 0 ? &#036;data-&gt;getChilds(&#036;data-&gt;parent_id,&#036;data-&gt;nome) : &#036;data-&gt;nome',


		'htmlOptions'=&gt;array('style'=&gt;'text-align:center;'),


	),		


	'ordem',





	array(


		'class'=&gt;'CButtonColumn',


	),


),

)); ?>

  • E grande questão é o seguinte…Queria listar na minha Grid as categorias dessa forma:

    Panelas > Caldeirões

    Panelas > Caçarolas

    Panelas > Caçarolas > Alumínio

    Panelas > Pressão

    Utensílios

    Mesas

De forma que eu pudesse passar o $parent_id e ele me retornasse os elementos:

Algo como $data->getChilds($data->parent_id,$data->nome);

Alguma ideia?

Ja pesquisei tem muitos lugares, mas nenhum na mesma situação que eu.

HEEEEEEEEEEEELP…

Talvez esta extensão possa te ajudar

http://www.yiiframework.com/extension/nestedsetbehavior/

Obrigado pela dica Luiz Reginaldo,

mas eu consegui resolver meu problema com essa função muito simples! Mas suei pra conseguir achar a solução…




//pega os pais a partir de uma filha

	public static function getStringParents($idParent,$nomeFinal) {

		$nome = $nomeFinal;

		while($idParent != 0){

			

			$model = Categoria::model()->findByPk($idParent);

			$nome = $model->nome.' > '.$nome;


			$idParent = $model->parent_id;

			

		}

		return $nome;

	}