簡體   English   中英

CodeIgniter:顯示兩個查詢結果,一個返回

[英]CodeIgniter : display two query result with one return

我正在嘗試顯示“類別”數據庫,這一部分非常簡單。 困難的部分是我需要計算“類別”數據庫中的子類別,並用一個表顯示它們。

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>

我只是在假設您只有一個表的情況下發布答案(您不需要為子類別使用單獨的表,但是如果您確實需要第二個表,則應該能夠根據我的答案得出此表)

您的模型

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM