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

时间:2017-07-04 14:59:02

标签: php laravel laravel-5 eloquent

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

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

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

这是我的控制器:

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'));
}

3 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

使用像这样的日期函数

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

答案 2 :(得分:0)

模型中的

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

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'));
}