I have two tables
products sale_items
-------- ----------
id id
code product_id
name quantity
price ...
...
count the number of sales per product, all in one query. I tried something like this, but it doesn’t work:
public function getProductsListing()
{
$this->db->select("products.id, products.code, products.name");
$this->db->from('products');
$this->db->join('sale_items','sum(COALESCE(quantity, 0)) as qte', false)
->where("registers_id = '{$this->session->register_id}' and sale_items.product_id = products.id", null, false);
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach (($query->result()) as $row) {
$data[] = $row;
var_dump($data);
}
return $data;
}
else
{
return false;
}
}
3
Answers
you can simply join table like this in codeigniter
You can use
group by
clause on product id:I don’t use CI, but I think you need to pass
false
as the second parameter toselect()
, to stop CI attempting to escape the column names.Notice I switched
SUM(COALESCE(quantity, 0))
toIFNULL(SUM(s.quantity), 0)
so theIFNULL()
runs on the aggregate instead of every row.