This tutorial is a very short one. How to sum the value from a column in a table? Let say you’ve table stocks [id, product, brand, quantity]. To sum the quantity value, you can apply the following code to your controller.
public function index()
{
$stocks = $this->paginate($this->Stocks);
//Count quantity
$total_quantity = $this->Stocks->find();
$count_quantity =$total_quantity->select(['sum' => $total_quantity->func()->sum('Stocks.quantity')])->first();
$sum_quantity = $count_quantity->sum;
$this->set(compact('stocks','sum_quantity'));
}
You can print the result using the following code in your view.
<?= $sum_quantity; ?>
That’s all. Happy coding :)