Laravel Carbon返回我0结果 [英] Laravel Carbon return me 0 results
问题描述
我需要为数据库中的用户获取本月的数据,所以我写:
I need to grab this month data for user in database so I write:
dd($user->products->where('paid',1)->where('created_at','>=', Carbon::now()->startOfMonth()->toDateString())->all());
我得到0条结果...
and I got 0 results...
当我尝试Carbon::now()->subMonth()
时效果很好,但过去30天还给我...
When I try Carbon::now()->subMonth()
its works good but return me last 30 days ...
我该如何解决?如何仅获取本月的数据?
How I can solve this? How to get only this month data ?
推荐答案
->toDateString()
导致查询查找string
值,而不是date
.有两种解决方法:
->toDateString()
is causing the query to look for a string
value, and not a date
. There's two ways to solve this:
(...)->where('created_at', '>=', Carbon::now()->startOfMonth())
// OR
(...)->whereDate('created_at', '>=', Carbon::now()->startOfMonth()->toDateString())
如果仅使用Carbon
变量,则Laravel知道要检查date
逻辑.另外,如果您使用的是string
,则可以使用->whereDate()
If you just use a Carbon
variable, Laravel knows to check for date
logic. Alternatively, if you're using a string
, you can override the where
logic to treat it as a date
by using ->whereDate()
这篇关于Laravel Carbon返回我0结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!