如何在Laravel中将created_at时间戳与Carbon日期进行比较?

huangapple go评论72阅读模式
英文:

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();

huangapple
  • 本文由 发表于 2020年1月4日 00:08:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定