Laravel:使用 Eloquent 将两个日期与今天进行比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44909177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:15:38  来源:igfitidea点击:

Laravel: Compare two dates against today with Eloquent

phplaravellaravel-5eloquent

提问by Przemek Wojtas

So I have events table which has start date and end date.

所以我有具有开始日期和结束日期的事件表。

What I want to do is a comparison between today and start date + end date so if today is between start and end, return that collection which will be displayed on page, if it isn't ignore that event.

我想要做的是今天和开始日期 + 结束日期之间的比较,所以如果今天在开始和结束之间,返回将显示在页面上的集合,如果它不是忽略该事件。

Problem is that when I retrieve an event I cannot access it as it is return that it doesn't exist in the collection, but it does after view is returned.

问题是,当我检索一个事件时,我无法访问它,因为它返回它在集合中不存在,但它在返回视图后访问。

Here's my controller:

这是我的控制器:

public function show($id)
{
    $today = date("Y-m-d");
    $today_dt = new DateTime($today);
    $event = Event::with('businesses')
        ->get();
    $test = $event->startdate;
    $test2 = $event->enddate;
    //something like if $today is not less that start date and not higher than end date, return that collection?
    dd($test);
    return view('events.showEvent', compact('event'));
}

回答by Oluwatobi Samuel Omisakin

If I understood your problem correctly, I think this should suffice:

如果我正确理解了您的问题,我认为这应该足够了:

$today = Carbon::today();
$event = Event::whereDate('startdate', '>', $today->format('Y-m-d'))
    ->whereDate('enddate', '<', $today->format('Y-m-d'))
    ->with('businesses')
    ->get();

I hope you did search the internet for this problem in the first place

我希望你首先在互联网上搜索这个问题

回答by Shahzaib Sheikh

use where date function like this

像这样使用 where 日期函数

$today = Carbon::now();
$event = Event::with('businesses')
           ->whereDate('startdate', '<', $today->format('Y-m-d'))
           ->whereDate('enddate', '>', $today->format('Y-m-d'))
           ->get();

回答by ZeroOne

in Model

在模型中

public function scopeOfToday($query){
    $today = \Carbon\Carbon::today()->format('Y-m-d');
    return $query->whereRaw("? BETWEEN startdate and enddate",$today);
}

in Controller

在控制器中

public function show($id)
{
    $event = Event::ofToday()->with('businesses')->get();

    $test = $event->startdate;
    $test2 = $event->enddate;
    //something like if $today is not less that start date and not higher than end date, return that collection?
    dd($test);
    return view('events.showEvent', compact('event'));
}