【问题标题】:Laravel search between dates no results when dates are the same (get results from today)Laravel 在日期之间搜索当日期相同时没有结果(从今天开始获取结果)
【发布时间】:2016-08-02 18:25:58
【问题描述】:

我有一个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();
}

【问题讨论】:

    标签: php laravel date between


    【解决方案1】:

    试试下面的代码

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

    这会将 DATETIME 字段转换为 DATE

    【讨论】:

    • 我实际上是用它来搜索生日,但按月和日。不知道我也可以在这样的约会中使用它。太棒了,谢谢你:)
    【解决方案2】:

    我认为问题在于您的日期字段很可能有一个时间组件,如果您要比较它是否在日期之间,您需要截断它。

    确保在控制器顶部导入 db 命名空间

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

    【讨论】:

    • 非常感谢,答案也很好:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多