laravel 5.0 中使用 FLUENT 的日期时间列的日期值

Date value of datetime column using FLUENT in laravel 5.0

如何使用 fluent 获取 laravel 5 中日期时间列的日期?

我想将此 2015-08-30 23:00:00 与此进行比较:

    $dt = Carbon::now();
    $d = $dt->toDateString();//this is the date only which i want to compare

有一个名为 DATE 的 mysql 函数,它像这样提取日期或日期时间表达式的日期部分 DATE(`datetime`) 但如果我使用它给我一个完整性错误。

以下是我尝试使用它的方式:

$reservations = \DB::table('reservations')
            ->select('reservations.id','DATE(reservations.datetime)')
            ->get();

没有人回答所以我会 post 我是如何临时解决它的:

Laravel 提供了一个叫做 Raw Expressions 的东西,所以我所做的是使用原始 select 来获取日期时间的日期字符串,如下所示:

     $reservations = \DB::table('reservations')
        ->select(\DB::raw('reservations.id, DATE(reservations.datetime)')
        ->get();

我的目标是将日期时间列中的日期与 Carbon 日期进行比较,我是这样做的:

     $dt = Carbon::now();
     $d = $dt->toDateString();//Only date from datetime

     $reservations = \DB::table('reservations')
        ->whereRaw("DATE(reservations.datetime) = '".$d."'")
        ->select(\DB::raw('reservations.id, DATE(reservations.datetime)')
        ->get();

我用 whereRaw 为 where 子句做了一个原始句子。

如果有人有更好的方法来做同样的事情,也许使用 Eloquent 我想知道它,因为 Eloquent 更安全一些...

正确的做法以及您正在寻找的是:

$query->whereDate('created_at', '=', date('Y-m-d'));

有关 whereDate() 的更多详细信息,请参见此处: http://laravel.com/api/5.0/Illuminate/Database/Query/Builder.html#method_whereDate http://laraveldaily.com/eloquent-date-filtering-wheredate-and-other-methods/

按照代码使用它获取日期'2016-07-14'的所有记录

 whereDate('date','=','2016-07-14')

如果您的日期在变量 $date 中可用,则使用以下代码

 whereDate('date',$date)

您可以使用 whereDate 来比较日期。流波纹管代码。

whereDate('date', '=', $date)

如果您提供 whereDate,则仅比较日期时间字段中的日期。