问题
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