需要获取当前月份的记录,但查询返回错误的结果。数据库中只有一条记录。但我得到了错误的当前月份计数
$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得到的结果
4条答案
按热度按时间noj0wjuj1#
“whereMonth”仅比较月份编号,而不比较年份
选项1:
选项2:
xdnvmnnf2#
这里的Item是模态的。
92vpleto3#
实际上,您需要使用
whereMonth
来获得完整的日期,而不仅仅是月份的整数等效值。此外,如果您只想显示recordcount,则可以执行以下操作:
bf1o4zei4#
避免使用
whereMonth()
和类似的“helper”方法。这是一个可怕的习惯,会导致不必要的低效查询。在本地机器上测试时,这可能无关紧要,但如果你足够幸运地让你的应用程序进入“野生”状态,并在1,000个并发用户中获得成功,这可能是成功与失败的区别。你的密码-
会产生类似以下的查询-
因为
month()
函数 Package 了creation_date
,所以服务器无法使用creation_date
上的任何可用索引。它也不必要对每一行执行该函数。阅读更多关于Non-SARGable Predicates的信息。正如@Heroherm所建议的,您应该使用
whereBetween()
-这将导致类似于以下内容的查询-
如果这不起作用,如前所述,请使用
->dd()
代替->get()
以查看发生了什么。