laravel 如何获取当月记录?

-1 mysql laravel eloquent

需要获取当月的记录,但查询返回错误的结果。数据库中只有一条记录。但我得到当月的错误计数

$data = UserData::select(
    DB::raw("count(phone) as total")
)
    ->whereMonth('creation_date', Carbon::now()->month)
    ->get();
return view('kpidata', compact('data'));
Run Code Online (Sandbox Code Playgroud)

这是 mysql 查询的结果, 在此处输入图像描述

这是我使用 laravel 查询得到的结果,在此处输入图像描述

小智 6

“whereMonth”仅比较月份数而不是年份

选项1:

UserData:select(DB::raw("count(phone) as total"))
    ->whereBetween('creation_date', 
        [
            Carbon::now()->startOfMonth(), 
            Carbon::now()->endOfMonth()
        ])
    ->get();
Run Code Online (Sandbox Code Playgroud)

选项2:

UserData:select(DB::raw("count(phone) as total"))
    ->whereYear('creation_date', Carbon::now()->year)
    ->whereMonth('creation_date', Carbon::now()->month)
    ->get();
Run Code Online (Sandbox Code Playgroud)