Example we have a table called transactions.Where transactions has 3 fields
Id | amount | created
We need to fetch last month’s summary by the created date. So, in cakephp we can write like below
public function report() { $targetDate = FrozenTime::now()->modify('1 month ago'); $query = $this->Transactions->find(); $query ->select( [ 'created', 'amount'=> $query->func()->sum('Transactions.amount') ] ) ->where([ 'Transactions.created >=' => $targetDate->startOfMonth(), 'Transactions.created <=' => $targetDate->endOfMonth() ]) ->group('Transactions.created'); $this->set("transactions",$this->paginate($query)); }
Here I have used cakephp FrozenTime class.
So, top in our class we have to use
use Cake\I18n\FrozenTime;
In view you can write below foreach loop to print data.
<?php foreach ($transactions as $transaction): ?> <tr> <td><?= $transaction->created->format("Y-m-d") ?></td> <td><?= $transaction->amount ?></td> /tr> <?php endforeach; ?>