Laravel Eloquent比较日期时间字段的日期

时间:2014-08-05 13:23:44

标签: php mysql datetime laravel-4

我想通过表达式从表中获取所有行:

table.date <= 2014-07-10

但如果该列包含日期时间,请说:

2014-07-10 12:00:00

但如果我这样做:

where('date', '<=', $date)

它不会获得该行。

我想这是因为$ date = 2014-07-10这让MySQL假设它是2014-07-10 00:00:00。

在常规MySQL中我会做

where DATE(date) <= $date

使用Laravel的Eloquent会等同于什么?

7 个答案:

答案 0 :(得分:55)

Laravel 4+为您提供以下方法:whereDay()whereMonth()whereYear()#3946)和whereDate()#6879)。< / p>

他们为您执行SQL DATE()工作,并管理SQLite的差异。

您的结果可以如此实现:

->whereDate('date', '<=', '2014-07-10')

有关更多示例,请参阅#3946和此Laravel Daily article的第一条消息。


更新:虽然上述方法很方便,但是如Arth所述,它对大型数据集效率低,因为必须在每条记录上应用DATE() SQL函数,从而丢弃可能的索引。

以下是进行比较的一些方法(但请阅读以下注释):

->where('date', '<=', '2014-07-10 23:59:59')

->where('date', '<', '2014-07-11')

// '2014-07-11'
$dayAfter = (new DateTime('2014-07-10'))->modify('+1 day')->format('Y-m-d');

->where('date', '<', $dayAfter)

注意:

  • 23:59:59可以(暂时)因为1秒的精确度,但看看这篇文章:23:59:59 is not the end of the day. No, really!
  • 请记住“零日期”情况(“0000-00-00 00:00:00”)。虽然应该避免这些“零日期”,但它们是许多问题的根源。如果需要,最好使字段可以为空。

答案 1 :(得分:6)

您是否考虑过使用:

where('date', '<', '2014-08-11')

你应该避免在MySQL中对索引列使用DATE()函数,因为这会阻止引擎使用索引。

<强>更新

由于对DATE()和索引的重要性似乎存在一些分歧,我创建了一个fiddle来展示差异,请参阅POSSIBLE KEYS

答案 2 :(得分:3)

您可以使用它来获取日期'2016-07-14'的所有记录

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

或使用其他代码进行动态日期

whereDate('date',$date)

答案 3 :(得分:1)

您可以使用此

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

如果您提供whereDate,则只比较datetime字段中的日期。

答案 4 :(得分:0)

如果您仍然想知道如何解决它。

我用

$protected $dates = ['created_at','updated_at','aired'];

在我的模特和我所在的地方

where('aired','>=',time())

所以只需使用unix来比较哪里。

在另一方面的视图中,您必须使用日期对象。

希望它有所帮助!

答案 5 :(得分:0)

这是我的逻辑: 如果您正在比较日期,那么您的方法应该是 whereDate,如果您比较完整的日期时间,那么您的方法将只在:

$calendar_alert = DB::table('calendar_alerts')->whereDate('when', '=', now()->format('Ym-d'))->where('when', ' >', now()->format('H:i:s'))->get();

答案 6 :(得分:0)

use Carbon\Carbon;

public function scopePublished($query)
{
  $now = Carbon::now();
  $date = Carbon::parse($now)->toDateString();
  $time = Carbon::parse($now)->toTimeString();
  return $query->whereDate('published_at', '<', $date)
  ->orWhere(function($query) use ($date, $time) {
    $query->whereDate('published_at', '=', $date)
    ->whereTime('published_at', '<=', $time);
  });
}
相关问题