CakePHP 3 - How to sum the values of the quantity column of several lines and show the result in the view?

0

I have Table Entradaestoques

  

id - prod - qtd

     

1 - soap - 10

     

2 - cloth - 7

     

3 - soap - 20

     

4 - disinfectant - 4

     

5 - soap - 20

     

6 - cloth - 3

I want to show in View

  

Soap: 50 units

     

Cloth: 10 pcs

How do I calculate the sum of the amount of the soap product and the other products in controller of CakePHP and send that sum to show in View ?

    
asked by anonymous 10.11.2016 / 20:44

1 answer

1

You can use SQL's SUM () function and cakePHP's ORM gives you the means to have easy access to it. In your case, inside the controller, you can do the following:

use Cake\ORM\TableRegistry;

//Sua classe de tabela, diagamos que você tenha criado a classe de tabela: ProdutoEstoque.php
$produto = TableRegistry::get('EntradaEstoques');

$query = $produto->find();

$quantidade_sabao = $query->select(['sum' => $query->func()->sum('sabao')]);

$quantidade_pano = $query->select(['sum' => $query->func()->sum('pano')]);

//Envia os valores para a view
$this->set([
    'quantidade_sabao' => $quantidade_sabao,
    'quantidade_pano' => $quantidade_pano,
]);

Within the view (Your HTML) you will have access to the value of each variable:

<p>Quandidade de Sabão: <?= $quantidade_sabao ?></p>
    
17.11.2016 / 21:59