CakePHP's Query Builder works basically in two steps. The first step you mount is query , in the second step you execute the query and it can return an object from your entity or a collection .
In the example you presented, you are only performing the first step, which is to mount the query. When you give echo
to your view , it is writing out the toString
method of Query Builder , not executing the query it has set up.
To execute 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 methods that make insert
, delete
or update
method execute()
. I recommend testing them to see how it works and how it works.
In your case, you could do as follows:
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 internally stores a colletion with the data of your query . It is populated when a colletion method is called 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')]);
}
References and recommended reading of CakePHP documentation: