我目前正在使用下面的代码根据
ID
总结数量
针对 mysql 数量列,只是想知道这是否是使用 codeigniter 的最佳实践?或者是否有更短的方法来执行此操作。
我的模型.php
public function sum_quantity_of_stacks($id){
$query = $this->db->query("SELECT *, SUM(qty) as total FROM stocks WHERE drug_id = '$id'");
return $query->row_array();
}
public function sum_quantity_of_request($id){
$query = $this->db->query("SELECT *,SUM(quantity) as total_request FROM med_request WHERE med_given = '$id' AND status = 'Approved'");
return $query->row_array();
}
然后是我的view.php
$id = $medicine['ID'];
$data['get_count'] = $this->Medicine_model->sum_quantity_of_stacks($id);
$data['get_request'] = $this->Medicine_model->sum_quantity_of_request($id);
$total_available = $data['get_count']['total'];
$total_given = $data['get_request']['total_request'];
echo $total_available - $total_given;
上面的代码为我提供了我的药品库存的当前可用库存。
不,没有这样的方法可以做到这一点,类似于你现在正在做的事情。
无法使用 SUM 功能选择其他列
但是查询生成器中有一个方法名称
select_sum()
可用,您可以通过它仅获得 SUM ,如
public function sum_quantity_of_stacks($id){
$this->db->select_sum('qty','total');
$this->db->where('drug_id',$id);
$query = $this->db->get('stocks');
$res = $query->row_array();
//now SUM is available in $res['total']
return $res['total'];
// or return $query->row_array();
}