在 codeigniter 中访问 num_rows 和 return 到 ajax

Acessing num_rows in codeigniter and return to ajax

这是我的模特:

public function fetch_customer_invoice($f_date,$t_date)
{
$this->db->select('invoice_id');
$this->db->from('invoice');
$this->db->where('date >=',$f_date);
$this->db->where('date <=',$t_date);
$res=$this->db->get();
 foreach($res->result() as $row)
 {
   $invoice=$row->invoice_id;
   $this->db->select('*');
   $this->db->from('invoice_products');
   $this->db->where('invoice_id',$invoice);
   $res=$this->db->get();
   return $res->result();
 }
}

这是我的控制器:

public function fetch_customer_invoice()
{
$from_date=$this->input->post('from_date');
$to_date=$this->input->post('to_date');
$data['res']=$this->revenue_reports_model- 
  >fetch_customer_invoice($from_date,$to_date);
echo json_encode($data);
}

脚本:

$('input[type="date"]').change(function() {
var from_date=$("#from_date").val();
var to_date=$("#to_date").val();
$.ajax({
    url: "<?php echo base_url(); ?>revenue_reports/fetch_customer_invoice/",
    dataType:'json',
    type: 'post',
    data : {"from_date" : from_date, "to_date" : to_date},
    success: function(data) {
      console.log(data.res);
    }
  });
}); 

此查询从特定日期的发票 table 中获取所有发票 ID。从我的 table 开始,该特定日期有 2 行,但是,模型 return 第一行结果 only.Why??我不知道错误在哪里,无论是在模型中还是在 ajax函数???请帮助..

希望对您有所帮助:

在模型方法中,您的 foreach 应该是这样的:

public function fetch_customer_invoice($f_date,$t_date)
{
   $this->db->select('invoice_id');
   $this->db->from('invoice');
   $this->db->where('date >=',$f_date);
   $this->db->where('date <=',$t_date);
   $res = $this->db->get();
   foreach($res->result() as $row)
   {
      $invoice=$row->invoice_id;
      $this->db->select('*');
      $this->db->from('invoice_products');
      $this->db->where('invoice_id',$invoice);
      $res = $this->db->get();
      $data[] =  $res->result(); 
      /* Or better use $res->row() if only one record per id*/
  }
 return $data;
}

您可以像这样使用 count() 方法:

public function fetch_customer_invoice()
{
    $from_date=$this->input->post('from_date');
    $to_date=$this->input->post('to_date');
    $results = $this->revenue_reports_model->fetch_customer_invoice($from_date,$to_date);
    $data['res']= $results;
    //$data['count']= count($results);
    echo json_encode($data);
}