CodeIgniter按日期筛选后统计不同状态数据行数实现问题
解决方案
1. 替换模型类的查询方法
你原来的get_records方法只能返回总条数,我们需要改写为匹配你统计需求的方法,直接把你测试可用的SQL转换为CodeIgniter查询构造器写法,补全所有表头对应的状态统计:
public function fetch_date($st_date,$end_date){ // select第二个参数设为false,防止CI自动转义sum表达式 $this->db->select(" sum(case when status = 'D' then 1 else 0 end) AS Draft, sum(case when status = 'U' then 1 else 0 end) AS Unpublish, sum(case when status = 'P' then 1 else 0 end) AS Publish, sum(case when status = 'A' then 1 else 0 end) AS Action, sum(case when status = 'UL' then 1 else 0 end) AS Unlisted, sum(case when status = 'S' then 1 else 0 end) AS Sold, sum(case when status = 'L' then 1 else 0 end) AS Let ", false); $this->db->from('crm_listings'); // 用CI的条件写法自动转义,避免SQL注入 $this->db->where('added_date >=', $st_date); $this->db->where('added_date <=', $end_date); // 直接返回单行统计结果,不需要遍历多条 return $this->db->get()->row(); }
注意:上面case条件里的status值(比如'D'/'U'等)请替换为你实际业务里对应状态的存储值,和你表头一一对应即可。
2. 修正控制器的表格渲染逻辑
因为我们返回的是单条统计结果,不需要用foreach循环遍历,直接取出对应字段填充到td里即可:
function fetch_status(){ $output =''; $startDate = ''; $endDate = ''; $this->load->model('crm/user_model'); if($this->input->post('startDate')){ $startDate = $this->input->post('startDate'); } if($this->input->post('endDate')){ $endDate = $this->input->post('endDate'); } // 调用模型方法获取统计结果 $stat = $this->user_model->fetch_date($startDate,$endDate); $output .= ' <div class="table-responsive"> <table class="table table-bordered table-striped"> <tr> <th>Draft</th> <th>Unpublish</th> <th>Publish</th> <th>Action</th> <th>Unlisted</th> <th>Sold</th> <th>Let</th> </tr> '; // 只要有任意状态统计值大于0就展示 if($stat && array_sum((array)$stat) > 0) { $output .= ' <tr> <td>'.$stat->Draft.'</td> <td>'.$stat->Unpublish.'</td> <td>'.$stat->Publish.'</td> <td>'.$stat->Action.'</td> <td>'.$stat->Unlisted.'</td> <td>'.$stat->Sold.'</td> <td>'.$stat->Let.'</td> </tr> '; } else { $output .= '<tr> <td colspan="7">No Data Found</td> </tr>'; } $output .= '</table>'; echo $output; }
内容的提问来源于stack exchange,提问作者JJM50
相关产品推荐
相关产品推荐

