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

如何用Eloquent查询获取月度和年度访客数量

获取月度和年度访客数量的实现方法

你可以利用Carbon的日期处理能力,结合Eloquent的查询方法来实现月度和年度访客统计,以下是具体代码:

月度访客数量

匹配当前月份的所有访客记录,有两种常用实现方式:

// 方式1:利用whereYear和whereMonth精准匹配
$month = Visitor::whereYear('time', Carbon::now()->year)
               ->whereMonth('time', Carbon::now()->month);
dd($month->count());
// 方式2:通过日期前缀模糊匹配(适合time字段为字符串格式的场景)
$monthDatePrefix = Carbon::now()->format('Y-m');
$month = Visitor::where('time', 'like', $monthDatePrefix . '%');
dd($month->count());

年度访客数量

匹配当前年份的所有访客记录,同样有两种实现方式:

// 方式1:利用whereYear精准匹配
$year = Visitor::whereYear('time', Carbon::now()->year);
dd($year->count());
// 方式2:通过年份前缀模糊匹配
$yearDatePrefix = Carbon::now()->format('Y');
$year = Visitor::where('time', 'like', $yearDatePrefix . '%');
dd($year->count());

如果需要统计指定年月的访客数,直接替换Carbon::now()为目标日期即可,比如统计2023年3月的访客:

$specifiedMonth = Visitor::whereYear('time', 2023)
                         ->whereMonth('time', 3);
dd($specifiedMonth->count());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:24:55