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

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

How to compare created_at timestamp with Carbon date In laravel?

问题

这是我的尝试:

  1. $month = Carbon::today();
  2. $currentMonth = $month->month;
  3. $thisMonthOrders = Order::where('place_id', $id)->where('stage', 9)->whereMonth('created_at', $currentMonth)->get();
  4. 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:

  1. $month = Carbon::today();
  2. $currentMont = $month->month;
  3. $thisMonthOrders = Order::where('place_id',$id)->where('stage',9)->whereDate('created_at',$currentMont)->get();
  4. dd($thisMonthOrders);

The output that it gives me is an empty array.

答案1

得分: 2

你需要在MySQL中使用MONTH函数,以及whereRaw来实现:

  1. $thisMonthOrders = Order::where('place_id', $id)
  2. ->where('stage', 9)
  3. ->whereRaw('MONTH(created_at) = ?', [$currentMonth])
  4. ->get();

然而,如果涉及多年份,可能会出现问题,除非你还加入了年份的检查。你可以尝试使用whereBetween来提高成功率:

  1. $start = Carbon::now()->startOfMonth();
  2. $end = $start->copy()->endOfMonth();
  3. $thisMonthOrders = Order::where('place_id', $id)
  4. ->where('stage', 9)
  5. ->whereBetween('created_at', [$start, $end])
  6. ->get();
英文:

You'll need to use the MONTH function in MySQL, along with a whereRaw:

  1. $thisMonthOrders = Order::where('place_id',$id)
  2. ->where('stage',9)
  3. ->whereRaw('MONTH(created_at) = ?',[$currentMont])
  4. ->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.

  1. $start = Carbon::now()->startOfMonth();
  2. $end = $start->copy()->endOfMonth();
  3. $thisMonthOrders = Order::where('place_id',$id)
  4. ->where('stage',9)
  5. ->whereBetween('created_at',[$start, $end])
  6. ->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:

确定