Laravel在日期之间搜索,当日期相同时没有结果(从今天开始获取结果)


Laravel search between dates no results when dates are the same (get results from today)

我有一个appointments table,其中我将约会开始日期和时间存储在datetime字段中。我有很多方法可以用来获得在特定日期或两个给定日期之间开始的约会。例如:

日历类别:

public function today()
{
    $start = Carbon::now()->hour('00')->minute('00')->second('00');
    $end = Carbon::now()->hour('23')->minute('59')->second('00');
    return Appointment::getAppointments($this->start, $this->end);
}
// public function tomorrow();
// public function thisMonth();

预约模式:

public static function getAppointments($start, $end)
{
    return static::whereBetween('date', array(
        $start->format('Y-m-d H:i'),
        $end->format('Y-m-d H:i')
    ))->get();
}

正如你所看到的,我需要设置小时、分钟和秒,因为否则,如果开始和结束日期相同,它将不会返回任何结果。是否可以简单地执行以下操作,然后仍然从该日期获得结果?

public function today()
{
    $start = Carbon::now();
    $end = Carbon::now();
    return Appointment::getAppointments($this->start, $this->end);
}
public static function getAppointments($start, $end)
{
    return static::whereBetween('date', array(
        $start->format('Y-m-d'),
        $end->format('Y-m-d')
    ))->get();
}

尝试以下代码

return static::whereBetween(Db:raw('DATE(date)'), array(
    $start->format('Y-m-d'),
    $end->format('Y-m-d')
))->get();

这将把DATETIME字段强制转换为DATE

我认为问题在于,如果要比较日期之间的时间,那么您的日期字段很可能有一个需要截断的时间分量。

确保在控制器的顶部导入数据库名称空间

use DB;

这应该将日期转换为Y-m-d,这样它就会落在您的日期之间

public static function getAppointments($start, $end)
{
    return static::whereBetween(DB::raw('CAST(date as DATE)', array(
        $start->format('Y-m-d'),
        $end->format('Y-m-d')
    ))->get();
}