2016-11-21 93 views
0

我試圖顯示'類別'數據庫,這部分是很容易的。困難的部分是我需要從「類別」數據庫中統計子類別並用一個表格顯示它們。CodeIgniter:顯示一個返回的兩個查詢結果

Category | Sub Category 
------------------------ 
Cat A |  5 
Cat B |  7 

這裏是我的型號:

function category() { 
$query = $this->db->get('category'); 
$result = $query->result_array(); 
foreach($query->row() as $q) { 
$this->db->where('subcat_id', $q['cat_id']); 
$query2 = $this->db->get('subcat'); 
if($query2) { 
    return true; 
} else { 
    return false; 
} 

這裏是我的控制器:

function dispaly_category() { 
$data['category'] = $this->mymodel->category(); 
$this->load->view('view', $data); 
} 

這裏是我的查看:

<table> 
<thead> 
    <th>Category</th> 
    <th>Subcategory</th> 
</thead> 
<tbody> 
    <?php foreach($category as $c) : ?> 
    <tr> 
    <td><?php echo $c->category_name; ?></td> 
    <td><?php echo (count subcat for the above category); ?></td> 
    </tr> 
    <?php endforeach; ?> 
</tbody> 
</table> 
+0

讓我看看你的全表結構,這看起來有點混亂 – sintakonte

回答

0

我只是發佈一個答案,假設你只有一個表(你不需要一個單獨的表的子類別,但如果你真的需要你的第二個表,你應該能夠根據我的答案派生出這個)

模型

function category() 
{ 
    $query = $this->db 
     ->select("c.*, count(cc.id) AS countSubCategories") 
     ->from("category c") 
     ->join("category cc", "cc.parent_id = c.cat_id","left") 
     ->group_by("c.id") 
     ->get(); 

    return $query->result(); 
} 

控制器

function display_category() 
{ 

    $arrViewData = array(
     'category' => $this->mymodel->category() 
    ); 
    $this->load->view('view', $arrViewData); 
} 

視圖

<table> 
<thead> 
    <th>Category</th> 
    <th>Subcategory</th> 
</thead> 
<tbody> 
    <?php foreach($category as $c) : ?> 
    <tr> 
     <td><?php echo $c->category_name; ?></td> 
     <td><?php echo $c->countSubCategories; ?></td> 
    </tr> 
    <?php endforeach; ?> 
</tbody> 
</table> 
相關問題