Cakephp 3 - How to sum column values amount of multiple rows and display the result in the view?

Asked

Viewed 363 times

0

I have the 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 the View

Soap: 50 units

Cloth: 10 pieces


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

  • Where is the code?.

  • Cakephp3 as is made SQL? has some code

  • I don’t know how to do this code in the cakephp controller.

  • Are you a beginner in Cakephp? @Thiagophilipp

  • 1

    in version 3.x yes, used the old 2.x.

  • http://book.cakephp.org/3.0/pt/retrieving-data-and-resultsets.html will help, given the experience of v2?

  • @Virgilionovic was checking this tutorial but not how to use in my specific case.

  • http://stackoverflow.com/a/32589142/6797930 has that link look at only!

  • you have any Entity ready that references this table?

  • Product Entity Stock created by Bake.

Show 5 more comments

1 answer

1

You can use the function SUM() SQL and cakephp’s ORM gives you easy access to it. In your case, within 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>
  • How do I sum all "Qtd" lines with productstoque_id = 1, put this result in the $quatidade_prod1 variable and display this information in the view?

  • I am not entirely sure, but I suspect that it is possible to use the Where() method in conjunction with the sum() method. It would look something like $quantity = $query->select(['Qtd' => $query->func()->sum('Qtd')->Where(['product_id' => 1]) ]), then use the set() method, to include the variable and make it available in the View.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.