You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Yii2中统计今日创建的条目数量?

基于MongoDB UTCDateTime的用户统计实现方案

嘿,看了你配置的TimestampBehavior和样本数据,已经正确把created_at存储为MongoDB的UTCDateTime类型了,这部分配置没问题!下面针对你的count_users函数,给出几种常见统计场景的实现:

1. 统计指定时间范围内的用户数量

比如要统计某一天、某一周或者任意时间段内注册的用户,直接利用Yii2的ActiveQuery查询即可:

public function count_users($startDateTime, $endDateTime)
{
    // 将传入的日期时间字符串转换为MongoDB UTCDateTime对象
    $startUtc = new \MongoDB\BSON\UTCDateTime(strtotime($startDateTime) * 1000);
    $endUtc = new \MongoDB\BSON\UTCDateTime(strtotime($endDateTime) * 1000);
    
    return static::find()
        ->where(['>=', 'created_at', $startUtc])
        ->andWhere(['<', 'created_at', $endUtc])
        ->count();
}

// 调用示例:统计2018年4月29日全天注册的用户
$dailyCount = $this->count_users('2018-04-29 00:00:00', '2018-04-30 00:00:00');

2. 按日期分组统计每日注册量

如果需要按天、按月分组统计用户注册趋势,用MongoDB的聚合查询会更高效:

public function count_users_by_day($startDate, $endDate)
{
    $startUtc = new \MongoDB\BSON\UTCDateTime(strtotime($startDate) * 1000);
    $endUtc = new \MongoDB\BSON\UTCDateTime(strtotime($endDate) * 1000);
    
    // 直接操作MongoDB集合进行聚合
    return static::getCollection()->aggregate([
        // 第一步:筛选时间范围内的数据
        [
            '$match' => [
                'created_at' => [
                    '$gte' => $startUtc,
                    '$lt' => $endUtc
                ]
            ]
        ],
        // 第二步:按日期分组统计数量
        [
            '$group' => [
                '_id' => [
                    '$dateToString' => [
                        'format' => '%Y-%m-%d',
                        'date' => '$created_at'
                    ]
                ],
                'userCount' => ['$sum' => 1]
            ]
        ],
        // 第三步:按日期排序
        [
            '$sort' => ['_id' => 1]
        ]
    ])->toArray();
}

3. 优化你的TimestampBehavior配置

顺带提一句,你当前的TimestampBehavior配置可以简化,不用手动创建DateTime对象,直接用time()函数更简洁,效果完全一致:

'timestamp' => [
    'class' => TimestampBehavior::className(),
    'attributes' => [
        ActiveRecord::EVENT_BEFORE_INSERT => 'created_at',
        ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at',
    ],
    'value' => function() {
        // time()返回当前UTC时间戳,乘以1000转成毫秒级
        return new \MongoDB\BSON\UTCDateTime(time() * 1000);
    },
]

注意点:MongoDB的UTCDateTime存储的是毫秒级时间戳,所以转换时一定要乘以1000,否则会出现时间偏移(变成1970年左右的时间),你的样本数据已经验证了这部分是正确的,继续保持就好。

内容的提问来源于stack exchange,提问作者Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:30:57