如何在laravel中获取当前月份记录?

krcsximq  于 2022-11-26  发布在  其他
关注(0)|答案(4)|浏览(379)

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

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

这是mysql查询enter image description here结果
这是我使用laravel查询enter image description here得到的结果

noj0wjuj

noj0wjuj1#

“whereMonth”仅比较月份编号,而不比较年份

选项1:

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

选项2:

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

xdnvmnnf2#

这里的Item是模态的。

$data = Item::select('*')
            ->whereMonth('created_at', Carbon::now()->month)
            ->get();
   
print_r($data);
92vpleto

92vpleto3#

实际上,您需要使用whereMonth来获得完整的日期,而不仅仅是月份的整数等效值。

$data = UserData::whereMonth('creation_date', Carbon::now())->get();

return view('kpidata', compact('data'));

此外,如果您只想显示recordcount,则可以执行以下操作:

$data = UserData::whereMonth('creation_date', Carbon::now())->count();
bf1o4zei

bf1o4zei4#

避免使用whereMonth()和类似的“helper”方法。这是一个可怕的习惯,会导致不必要的低效查询。在本地机器上测试时,这可能无关紧要,但如果你足够幸运地让你的应用程序进入“野生”状态,并在1,000个并发用户中获得成功,这可能是成功与失败的区别。
你的密码-

$data = UserData::select(
    DB::raw("count(phone) as total")
)
    ->whereMonth('creation_date', Carbon::now()->month)
    ->get();

会产生类似以下的查询-

select count(phone) as total
from users
where month(creation_date) = :month

因为month()函数 Package 了creation_date,所以服务器无法使用creation_date上的任何可用索引。它也不必要对每一行执行该函数。阅读更多关于Non-SARGable Predicates的信息。
正如@Heroherm所建议的,您应该使用whereBetween()-

$data = UserData::selectRaw('count(phone) as total')
    ->whereBetween('creation_date',
        [
            Carbon::now()->startOfMonth()->format('Y-m-d'),
            Carbon::now()->endOfMonth()->format('Y-m-d')
        ]
    )
    ->get();

这将导致类似于以下内容的查询-

select count(phone) as total
from users
where creation_date between :start and :end

如果这不起作用,如前所述,请使用->dd()代替->get()以查看发生了什么。

相关问题