2013-08-07 83 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属性,以便您可以在视图中获取该值 –