You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CodeIgniter 3中统计各开发项目关联的房产记录总数?

解决方案:在CodeIgniter 3中实现每个开发项目的房产总数展示

问题分析

当前代码存在三个核心问题:

  1. 模型方法返回的是完整结果数组,而非统计数量
  2. 控制器调用计数方法时未传递必要的empreendimento_id参数
  3. 视图逻辑未针对“每个项目对应单独计数”做循环处理

1. 修正模型的计数方法

将countImoveisEmpreendimentos改为直接返回符合条件的记录数,而非结果集:

public function countImoveisEmpreendimentos($empreendimento_id)
{
    $this->db->where('empreendimento_id', $empreendimento_id);
    // 直接获取符合条件的记录总数
    return $this->db->count_all_results('ci_properties');
}

或者使用COUNT()聚合查询的写法:

public function countImoveisEmpreendimentos($empreendimento_id)
{
    $this->db->select('COUNT(*) as total_imoveis');
    $this->db->from('ci_properties');
    $this->db->where('empreendimento_id', $empreendimento_id);
    $query = $this->db->get();
    return $query->row()->total_imoveis;
}

2. 调整控制器逻辑,为每个项目绑定计数

遍历开发项目列表,给每个项目添加对应的房产计数:

public function index()
{   
    // 获取所有开发项目
    $lista = $this->empreendimentos_model->getEmpreendimentos();
    
    // 为每个项目添加房产计数(假设项目表主键为id)
    foreach ($lista as &$item) {
        $item['count_imoveis'] = $this->empreendimentos_model->countImoveisEmpreendimentos($item['id']);
    }
    
    $dados = array(
        "empreendimentos" => $lista,
        "view" => 'empreendimentos_list',
        "count_empreendimentos" => $this->empreendimentos_model->countEmpreendimentos()
    );

    $this->load->view('empreendimentos_list', $dados);
}

3. 修改视图,循环展示每个项目的计数

遍历项目列表,逐个输出对应房产数量:

<?php foreach ($empreendimentos as $emp): ?>
    <li class="list-inline-item" style="width: 110px;">
        <a href="#"><?= $emp['count_imoveis']; ?> imóveis</a>
    </li>
<?php endforeach; ?>

性能优化(可选)

如果项目数量较多,逐个查询会产生N+1性能问题,可修改getEmpreendimentos方法,通过左连接一次性获取所有项目及对应房产数:

public function getEmpreendimentos()
{
    $this->db->select('e.*, COUNT(p.id) as total_imoveis');
    $this->db->from('empreendimentos e'); // 替换为你的开发项目表名
    $this->db->join('ci_properties p', 'e.id = p.empreendimento_id', 'left');
    $this->db->group_by('e.id');
    return $this->db->get()->result_array();
}

此时控制器无需额外循环调用计数方法,视图直接使用$emp['total_imoveis']即可。

内容的提问来源于stack exchange,提问作者Mike Otharan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 20:35:18