How to get count of items which are created today in yii2?

杀马特。学长 韩版系。学妹 提交于 2019-12-13 03:14:29

问题


Sample data in my collection : created_at : 2018-04-29 05:25:28.000Z

I'm using TimestampBehavior,

'timestamp' => [
            'class' => TimestampBehavior::className(),
            'attributes' => [
                ActiveRecord::EVENT_BEFORE_INSERT => 'created_at',
                ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at',
            ],
            'value' => function() { $now = new \DateTime('NOW'); return new \MongoDB\BSON\UTCDateTime(strtotime($now->format("Y-m-d H:i:s"))*1000); },
        ],

This is my count function :

 public function count_users () {
       $cnt = Users::find ()->select (['_id', 'created_at'])->where (['created_at'=>date ('Y-m-d')])->all ();
       return count ($cnt);
 }

How to use find select with a date?


回答1:


You could use the count() function

You could use the count() function and new Expression('NOW()')

public function count_users () {
       $cnt = Users::find ()->select (['_id', 'created_at'])
        ->where (['created_at' => new \yii\db\Expression('curdate()')]->count();
       retur $cnt;
 }

yii-db-query

yii-db-query#count()-detail




回答2:


Change your where condition like below and try

public function count_users () {
       $cnt = Users::find ()->where('DATE(created_at)=CURDATE()')->count();
       return $cnt;
}

yii-db-query#count()-detail




回答3:


You can reduce it to one-liner by using count() as per suggestions above or using scalar()

scalar(): returns the value of the first column in the first row of the query result.

public function count_users(){
    return Users::find()
           ->select([new \yii\db\Expression('COUNT(id) as total')])
           ->where(['DATE(created_at)'=>new \yii\db\Expression('CURDATE()')])
           ->scalar();
}


来源:https://stackoverflow.com/questions/50083897/how-to-get-count-of-items-which-are-created-today-in-yii2

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