laravel 中碳的每月数据

maf*_*tis 1 php laravel php-carbon

我想按月而不是按天计算注册用户数。

例子

如果我有这样的代码:

$newUsers = User::where('created_at', '<=', now()->subdays(30))->count();
Run Code Online (Sandbox Code Playgroud)

它将返回过去 30 天的用户,假设今天是15th本月,那么结果将是从上个月15th到本月15th

这不是我想要的!

我想要的是计算从1st本月到30

这意味着如果今天是我从到15的用户数,而上个月的用户数为零。1st15

如何得到它?

Tha*_*han 6

您可以whereMonth()在 Laravel 中使用查询生成器的函数。

$usersCount = User::whereMonth(
    'created_at',
    Carbon::now()->format('m')
)->count();
Run Code Online (Sandbox Code Playgroud)

编辑

匹配确切的月份(月份与年份)

$usersCount = User::whereMonth(
    'created_at',
    Carbon::now()->format('m')
)->whereYear(
    'created_at',
    Carbon::now()->format('Y')
)->count();
Run Code Online (Sandbox Code Playgroud)