我目前正在使用以下代码汇总基于ID
的数量
定位mysql数量列,只是想知道这是否是使用codeigniter的最佳做法?或者是否有更短的方法来执行此操作。
我的Model.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;
以上代码为我提供了当前可用的药品库存。
答案 0 :(得分:0)
不,没有这样的方法可以做到这一点,类似于你现在正在做的事情。
选择其他不具备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();
}