Issue
I would like to show only the events for which startdate begins as of tomorrow. How can I proceed ? For the moment it's taking h:i:s into account as well.
public function display()
{
$now = date('Y-m-d H:i:s');
$this->loadModel('Events');
$events = $this->Events
->find()
->contain(['Categories', 'Venues'])
->limit(5)
->order(['events.startdate' => 'ASC'])
->where(['events.startdate >' => $now]);
$this->set('upcomingEvents', $events);
}
I tried this but it's not working:
public function display()
{
$now = date('Y-m-d');
$this->loadModel('Events');
$events = $this->Events
->find()
->contain(['Categories', 'Venues'])
->limit(5)
->order(['events.startdate' => 'ASC'])
->where(['date_format("%Y-%m-%d", events.startdate)' => $now]);
$this->set('upcomingEvents', $events);
}
Solution
No need to format the date in the query and lose the indexing functionality, instead compare against a datetime string that uses 00:00:00
for the time part, eg the start of the day.
You can achieve this easily with date('Y-m-d 00:00:00')
, however that would be today, not tomorrow, you'd need to feed date()
with a timestamp like date('Y-m-d 00:00:00', strtotime('+1 day'))
.
You can also use the datetime functionality that ships with CakePHP. Today \Cake\Chronos\Date::tomorrow()
would create a date object representing 2021-10-06
where the time part will always be 00:00:00
.
->where(['Events.startdate >=' => \Cake\Chronos\Date::tomorrow()])
The ORM will automatically format the date object accordingly to the column type, so for your I suppose DATETIME
column, it would end up as 2021-10-06 00:00:00
in the SQL.
See also
Answered By - ndm
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.