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: