cakephp: how to make NOW() work in search conditio

2020-07-14 05:25发布

I'm trying to get all records with date greater then now. I tried this but it doeasnt work:

$all_dates = $this->TourDate->find('all', array('conditions' => array('TourDate.date >=' => 'NOW()'), 'order' => array('TourDate.date ASC')));

If I replace NOW() with the current date it works. Why's that?

标签: cakephp mysql
5条回答
对你真心纯属浪费
2楼-- · 2020-07-14 05:37

hsz is correct. Cake is interpreting the NOW() condition as the string 'NOW()'. Providing a full SQL snippet in your conditions will work, as hsz suggests.

You might be tempted to use date('Y-m-d H:i:s') in place of NOW() (as I suggested in the first version of this answer). Don't do it! As hsz points out below, this will prevent the query from being cached.

查看更多
乱世女痞
3楼-- · 2020-07-14 05:41

'conditions' => array('TourDate.date >= NOW()')

Otherwise, cakephp will quote the NOW() function, and mysql will think of it as a string.

查看更多
神经病院院长
4楼-- · 2020-07-14 05:47

I do not use CakePHP but I am pretty sure that your 'NOW()' is parsing to string and finally you got something like

TourDate.date >= 'NOW()'

Maybe you should just try

array('TourDate.date >= NOW()')

as a value only instead of spliting it to key => value style ?

查看更多
Evening l夕情丶
5楼-- · 2020-07-14 05:51

If you are looking for a way to do it with PHP-function istead of MySQL-functions you don't have to use the verbous format $conditions = array('begin >' => date('Y-m-d H:i:s')), MySQL understands the shorter 'c' preset of PHPs date() for ISO 8601 dates with $conditions = array('begin >' => date('c')).

I like this for doing queries like 'begin >' => date('c', strtotime("+4 weeks")), which is very readable code and great to debug when you look at the SQL-Queries.

查看更多
孤傲高冷的网名
6楼-- · 2020-07-14 05:54

I believe CakePHP strips out any SQL like functions to prevent a SQL injection attacks. Much as it annoys me, I usually use the date('Y-m-d H:i:s') trick too.

查看更多
登录 后发表回答