2013-08-07 180 views
0

如何從Codeigniter中的數據庫獲得分層數據。我讀了這一點: http://www.sitepoint.com/hierarchical-data-database/ 而我呢好事,但我不能優化這個教程,我的模型,CONTROLER和看法Codeigniter從數據庫獲取嵌套的分層數據

Default Category 
    |----- Sub category 
      | ----One more category 
       |----- Somthing else 

我嘗試,但不顯示子類別:

我的模型:

public function fetchChildren($parent, $level) {  
     $this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' "); 
      foreach($this->handler->result() as $row) { 
       $this->data[$row->id] = $row; 
       //echo str_repeat(' ',$level).$row['title']."\n"; 
      } 

      return $this->data; 

}

控制器:

$this->data['node'] = $this->categories_model->fetchChildren(' ',0); 

瀏覽:

<table class="module_table"> 
    <thead> 
     <tr> 
      <th><?php echo lang('categories_table_title'); ?></th>  
     </tr> 
    </thead> 

    <tbody> 
     <?php foreach ($node as $row) : ?> 
     <tr> 
      <th> <?php echo str_repeat('|----', 0+1). $row->title ?> </th> 
     </tr> 
     <?php endforeach; ?> 
    </tbody> 

</table> 

和輸出是:

----Default 
----Default 
----Test Category 1 
----Seccond Test Category 1 
----Another Test Category 1 

當我做這個模型的所有工作正常,但是當我嘗試在DC型和循環調用視圖我有結果像上面的例子:

這項工作onlu在模型:

public function fetchChildren($parent, $level) {  
     $this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' "); 
      foreach($this->handler->result() as $row) { 
      echo str_repeat('|-----',$level).$row->title."\n"; 
      $this->fetchChildren($row->title, $level+1); 
      } 

      return $this->data; 

}

而像輸出我有:

Default 
    |----Test Category 1 
    |----Seccond Test Category 1 
     |----Another Test Category 1 

任何一個有溶液或例如感謝。

回答

0

嘗試存儲每個類別的等級值。

在你的模型:

public function fetchChildren($parent, $level){ 
    $this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' "); 
    foreach($this->handler->result() as $row) { 
     $row->level = $level; 
     $this->data[] = $row; 
     $this->fetchChildren($row->title, $level+1); 
    } 
    return $this->data; 
} 

在你的控制器:

$this->data['node'] = $this->categories_model->fetchChildren(' ',0); 

在你看來

<table class="module_table"> 
    <thead> 
     <tr> 
      <th><?php echo lang('categories_table_title'); ?></th>  
     </tr> 
    </thead> 
    <tbody> 
     <?php foreach ($node as $row) : ?> 
     <tr> 
      <th><?php echo str_repeat('|----', $row->level). $row->title ?> </th> 
     </tr> 
     <?php endforeach; ?> 
    </tbody> 
</table> 
+0

*** $按行>級別***是函數的參數沒有Db obj。我可以在視圖中放置什麼值來取代*** $ row-> level ***我str_repeat – Jony

+0

而且我還有一些類似於上面的輸出 – Jony

+0

@Jony是否更新過模型函數?我爲數據庫中的每個結果設置了level屬性,以便您可以在視圖中獲取該值 –