【问题标题】:Laravel ORM, date compareLaravel ORM,日期比较
【发布时间】:2025-11-27 14:40:01
【问题描述】:

我正在使用 Laravel 框架。

我想要这一天的所有行。这是我尝试过的:

DB::table('users')->where('created_at', '>=', date('Y-m-d H:i:s'))

(字段created_at在数据库中表示,格式为:Y-m-d H:i:s)。

【问题讨论】:

  • my own question 的可能副本,其中使用了 Eloquent 以及 Fluent。

标签: php laravel orm


【解决方案1】:

嗯……这个问题有一个很好的答案,现在似乎已经消失了。*

原来是这样的:

User::where('created_at', '>=', new DateTime('today'))

注意:如果您将此代码放在带有命名空间的文件中,或者将来可能会使用命名空间,则应在 DateTime 类前面加上反斜杠:new \DateTime('today')

* https://*.com/questions/15052679/laravel-framework-how-to-get-today-queries

【讨论】:

  • 漂亮地放在一起。
  • 这个答案让我的大脑走上了正轨。 SomeModel::where('whatever', '=','0000-00-00')
  • 给定的链接已损坏...还有其他选择吗?
【解决方案2】:

date('Y-m-d H:i:s') 返回现在的日期。

如果您想要一天开始的结果,可以将其替换为 date('Y-m-d').' 00:00:00'

如果您想要过去 24 小时的结果,可以将其替换为 date('Y-m-d H:i:s',time()-86400) (86400 = 24*60*60)

【讨论】:

    【解决方案3】:

    对于那些只需要比较日期而不需要时间的人,Lavarel 提供了一个方便的函数whereDate

    User::whereDate('created_at', '>=', date('Y-m-d'));
    

    http://laraveldaily.com/eloquent-date-filtering-wheredate-and-other-methods/

    【讨论】:

      【解决方案4】:

      我知道该主题很旧,但可能有人会尝试从搜索引擎中找到解决方案。

      你可以使用:

      User::whereDate('created_at', '=', Carbon::today()->toDateString());
      

      如果您想了解更多关于 Laravel 中使用 where 进行日期比较的信息,可以访问此链接。

      Eloquent date filtering: whereDate() and other methods

      【讨论】:

        【解决方案5】:

        简单地说:

        DB::table('users')->where('created_at', '>=', date('Y-m-d'). ' 00:00:00')
        

        获取这一天的所有行时(时间应为 00:00:00),因此请确保将日期条件设置为当前日期加上 00:00:00 即

        date('Y-m-d'). ' 00:00:00'
        

        【讨论】:

        • 虽然这段代码 sn-p 可以解决问题,including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
        【解决方案6】:

        使用whereDate

        $users = DB::table('users')
                        ->whereDate('created_at', '2016-12-31')
                        ->get();
        

        您可能使用的其他功能是:whereDate / whereMonth / whereDay / whereYear / whereTime

        【讨论】: