[英]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.