英文:
How to compare created_at timestamp with Carbon date In laravel?
问题
这是我的尝试:
$month = Carbon::today();
$currentMonth = $month->month;
$thisMonthOrders = Order::where('place_id', $id)->where('stage', 9)->whereMonth('created_at', $currentMonth)->get();
dd($thisMonthOrders);
它给我返回的输出是一个空数组。
英文:
I have orders table , I want to get orders that have been created at this month only (delivery process happens at the same day).
I want to compare between the carbon date which refers to this current month with the created_at field of type timestamps for orders.
This is my attempt:
$month = Carbon::today();
$currentMont = $month->month;
$thisMonthOrders = Order::where('place_id',$id)->where('stage',9)->whereDate('created_at',$currentMont)->get();
dd($thisMonthOrders);
The output that it gives me is an empty array.
答案1
得分: 2
你需要在MySQL中使用MONTH
函数,以及whereRaw
来实现:
$thisMonthOrders = Order::where('place_id', $id)
->where('stage', 9)
->whereRaw('MONTH(created_at) = ?', [$currentMonth])
->get();
然而,如果涉及多年份,可能会出现问题,除非你还加入了年份的检查。你可以尝试使用whereBetween
来提高成功率:
$start = Carbon::now()->startOfMonth();
$end = $start->copy()->endOfMonth();
$thisMonthOrders = Order::where('place_id', $id)
->where('stage', 9)
->whereBetween('created_at', [$start, $end])
->get();
英文:
You'll need to use the MONTH
function in MySQL, along with a whereRaw:
$thisMonthOrders = Order::where('place_id',$id)
->where('stage',9)
->whereRaw('MONTH(created_at) = ?',[$currentMont])
->get();
However, you'll have issues when you have multiple years, unless you also add in a YEAR check. You might have better luck with whereBetween
instead.
$start = Carbon::now()->startOfMonth();
$end = $start->copy()->endOfMonth();
$thisMonthOrders = Order::where('place_id',$id)
->where('stage',9)
->whereBetween('created_at',[$start, $end])
->get();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论