I need to count the today created account in Cake 3

馋奶兔 提交于 2020-01-06 16:11:07

问题


I need to count the users, but my condition is only if their account have been created today. I have a users table with a created field (datetime) for each rows. How can i do it in Cakephp, i didn't find the answer in the documentation.

$usersNewCount = Number::format($this->Users->find()->where(['created' => 'CURDATE()'])->count());

I tried with CURDATE, and of course it's not working, i guess Cakephp has a specific function for te datetime field ?


回答1:


What you are doing there won't work for various reasons.

  1. You cannot pass SQL snippets in the value part of the conditions array, it will be escaped and you'll end up with a string comparison like created = 'CURDATE()', you'd either have to pass the whole condition as a string, or use raw expressions.

  2. Even when properly passing CURDATE(), the comparison won't work as the created column has a time part.

While it is possible to circumvent the former problem by transforming the column, you should try to avoid that whenever possible! Comparing to calculated columns like DATE(created) = CURDATE() will make using indices impossible, and thus massively degrade performance!

So unless you have an extra column that holds just the date part, your best bet is a BETWEEN comparison which is the equivalent to a >= x AND a <= y, and in order to stay cross DBMS compatible, this is best to be done by passing dates from PHP, ie not using DBMS specific date and time functions like CURDATE().

$this->Users
    ->find()
    ->where(function (\Cake\Database\Expression\QueryExpression $exp, \Cake\ORM\Query $query) {
        $from = (new \DateTime())->setTime(0, 0, 0);
        $to = (new \DateTime())->setTime(23, 59, 59);
        return $exp->between('Users.created', $from, $to, 'datetime');
    })
    ->count()

This will create a query similar to

SELECT
    (COUNT(*)) AS `count`
FROM
    users Users
WHERE
    Users.created BETWEEN '2015-05-26 00:00:00' AND '2015-05-26 23:59:59'

See also

  • API > \Cake\Database\Expression\QueryExpression::between()



回答2:


You can do it this way

$usersNewCount = Number::format($this->Users->find()->where([
    'DATE(created) = CURDATE()'
])->count());

Note that passing it in form where(['DATE(created)' => 'CURDATE()']) will not work, since CURDATE() will be interpreted as a string.




回答3:


When doing 'created' => 'CURDATE()' you are checking for a complete match, getting '2015-05-26', without a time. You need to check for a time interval:

$usersNewCount = Number::format(
    $this->Users->find()->where([
        'created >=' => date('Y-m-d').' 00:00:00',
        'created <=' => date('Y-m-d').' 23:59:59'
    ])->count());


来源:https://stackoverflow.com/questions/30446859/i-need-to-count-the-today-created-account-in-cake-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!