2012-04-22 122 views
0

我想分类树,以显示它是这样的:CakePHP的树模型结构

cat1 
    subcat1 
    subcat2 
    subcat3 
     subsubcat1 
cat2 
    subcat1 
... 

我有这个表:

CREATE TABLE IF NOT EXISTS `kategorie` (
    `id` int(11) NOT NULL auto_increment, 
    `name` varchar(256) collate utf8_polish_ci NOT NULL, 
    `father` int(11) NOT NULL default '-7', 
    PRIMARY KEY (`id`), 
    UNIQUE KEY `name` (`name`) 
) 

所以每个记录只包含自己和父ID(我无法添加左侧和右侧的ID)。

现在我做了这个模式:

class Category extends AppModel 
    { 
     public $name = 'Category'; 
     public $useDbConfig = 'external'; 
     public $useTable = 'kategorie'; 

     var $belongsTo = array( 
      'ParentCategory' => array( 
       'className' => 'Category', 
       'foreignKey' => 'father' 
     )); 

     var $hasMany = array( 
      'ChildCategory' => array( 
       'className' => 'Category', 
       'foreignKey' => 'father' 
     ));  

    } 

和控制器:

class CategoriesController extends AppController { 

     public function beforeFilter() 
     { 
      parent::beforeFilter(); 
      //$this->Auth->allow('add','logout'); 
     } 

     public function index() 
     { 
      $res = $this->Category->find('all'); 
      //$this->set('categories', $this->Category->find('all')); 
      debug($res); die;   
     } 
    } 

调试输出是这样的:

array(
    (int) 0 => array(
     'Category' => array(
      'id' => '1', 
      'name' => 'catname', 
      'father' => '2' 
     ), 
     'ParentCategory' => array(
      'id' => '2', 
      'name' => 'catname', 
      'father' => '3' 
     ), 
     'ChildCategory' => array(
      (int) 0 => array(
       'id' => '161', 
       'name' => 'catname', 
       'father' => '1' 
      ) 
     ) 
    ), 
    (int) 1 => array(
     'Category' => array(
      'id' => '2', 
      'name' => 'catname', 
      'father' => '3' 
     ), 
     'ParentCategory' => array(
      'id' => '3', 
      'name' => 'catname', 
      'father' => '4' 
     ), 
     'ChildCategory' => array(
      (int) 0 => array(
       'id' => '1', 
       'name' => 'catname', 
       'father' => '2' 
      ), 
      (int) 1 => array(
       'id' => '5', 
       'name' => 'catname', 
       'father' => '2' 
      ), 
      (int) 2 => array(
       'id' => '489', 
       'name' => 'catname', 
       'father' => '2' 
      ) 
     ) 
    ), 
... 

所以basicly我得到类别的数组对象(这些对象的数量是类别的数量(全部,甚至是子类别)。每个类别都有一个pa租赁类别和子类别列表...

这不是我想要的,因为我将不得不“手动”解析数组来建立类别树,并且它会很慢,因为我必须找到具有指定类别ID在数组中(类别ID不是它的索引在数组中)...

也许some1知道任何特殊技巧来获得一个很好的,有用的类树?

回答

2

尝试查看find方法的其他参数。您可以尝试使用

$res = $this->Category->find('threaded'); 

您可以在http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-threaded找到更多详细信息。

+0

嗯,这将是伟大的,但它需要提交'parent_id',我有领域'父',并且不能改变它 - 是否有任何把这个字段名称映射到'parent_id'的技巧?这是奇怪的 - 蛋糕应该提供一些参数,这将是parent_id在表中的名称... ... – user606521 2012-04-22 18:20:18

+2

在CakePHP 2.1中找到anserw - >使用find('threaded',array('parent'=>'father')); – user606521 2012-04-22 21:52:14

+1

您介意将我的答案标记为已接受的答案吗? – Arno 2012-04-23 16:03:46