2012-04-22 126 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