在Laravel中从数据库中获取特定月份的所有记录

rt4zxlrg  于 7个月前  发布在  其他
关注(0)|答案(3)|浏览(84)

在我的数据库中,我有此预订记录

App\Reservation {#2632
     id: 1,
     user_id: 7,
     rest_id: 23,
     reservation_date: "2019-08-29",
     from_time: "16:00:00",
     to_time: "00:00:00",
     count_of_people: 15,
     loyalty_points: 100,
     confirme: 2,
     cancle: 0,
     surveySended: 0,
     surveyAnswer: 0,
     created_at: null,
     updated_at: null,
   },

字符串
在我的控制器中,我有这样的代码,试图检索本月的所有预订:

public function getRestAdmin(Request $request,$rest_id)
{

$restaurant=Restaurant::find($rest_id);
  $today=\Carbon\Carbon::today();
//reservations made this month
$reservations=$restaurant->reservations()->where('confirme',2)->whereBetween('reservation_date',[$today->startOfMonth(),$today->endOfMonth()])->get();
 }


但我总是得到空!!

wecizke3

wecizke31#

假设你在数据库中有这些日期的预订,试着让Carbon在查询之前直接做繁重的工作(而不是首先设置为今天):

$start = new Carbon('first day of this month');
$end = new Carbon('last day of this month');

字符串
然后将变量添加到查询中:

whereBetween('reservation_date',[$start, $end]) ...


你也可以在Carbon上使用这个方法:

$start = Carbon::now()->startOfMonth();

ewm0tg9j

ewm0tg9j2#

Carbon强制格式化

$reservations = $restaurant
    ->reservations()
    ->where('confirme',2)
    ->whereBetween('reservation_date',[
        $today->startOfMonth()->format('Y-m-d'),
        $today->endOfMonth()->format('Y-m-d')
    ])->get();

字符串

qjp7pelc

qjp7pelc3#

也可以使用whereMonth和类似的whereYear

$month = 1; // january 
$reservations->whereMonth('created_at', $month)
$year = 2022; 
$reservations->whereYear('created_at', $year)

字符串

相关问题