Contrutor de Queries

Asked

Viewed 53 times

0

I am learning about cakephp and would like a help.

I have to do the sum of a column in my table (Postgres use).

I’m trying to use the sum() function of the cake itself.

My controller

use Cake\ORM\TableRegistry;

public function index()
{
   $contratacoes = TableRegistry::get('Contratacoes');
   $query = $contratacoes->find();
   $soma_financiamento = $query->select(['sum'   
    =>$query->func()->sum('vlr_financiamento')]);
   $this->set(['soma_financiamento' => $soma_financiamento]);
}

My view, just to test

<?= $soma_financiamento; ?>

Only this is coming out:

SELECT (SUM(vlr_financiamento)) AS "sum" FROM contratacoes Contratacoes

Could someone help me, please.

1 answer

0


The Query Builder Cakephp works basically in two steps. The first step is to query, in the second step you perform the query and she can return to you an object of her Entity or a Collection.

In the example you presented, you are only running the first step, which is to mount the query. When you do echo in his view, he is excommunicating the method toString of Query Builder, and not executing the query it mounted.

To run the query and return an object with the data from your database, you can use one of the following methods: all(), toArray(), first(), extract() and for methods that do insert, delete or update the method execute(). I recommend testing them to see how they function and their behavior.

In your case, you could do it this way:

use Cake\ORM\TableRegistry;

public function index()
{
   $contratacoes = TableRegistry::get('Contratacoes');
   $query = $contratacoes->find();
   $soma_financiamento = $query
      ->select(['sum' =>$query->func()->sum('vlr_financiamento')])
      ->first();

   // Descomente a linha abaixo para ver o resultado da query
   // debug($soma_financiamento);

   $this->set(['soma_financiamento' => $soma_financiamento->sum]);
}

There are other ways to do this. The Query Builder stores internally a colletion with the data of your query. It is populated when it is called a method of colletion with the current state of its Query Builder.

So another possible solution is:

use Cake\ORM\TableRegistry;

public function index()
{
   $contratacoes = TableRegistry::get('Contratacoes');
   $query = $contratacoes->find();

   $this->set(['soma_financiamento' => $query->sumOf('vlr_financiamento')]);
}

Cakephp Documentation References and Recommended Reading:

Browser other questions tagged

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