【问题标题】:Check if date has expired Laravel Date Field Type SQL检查日期是否已过期 Laravel 日期字段类型 SQL
【发布时间】:2017-09-13 22:20:53
【问题描述】:

在我的应用程序中,我必须检查某个日期是否已过期,因此必须发送电子邮件。日期保存在Clients 表中。如何在检索日期上添加 5 天,以便检查它是否会在 5 天内过期?我到现在为止的功能。

public function handle() {

    $users =\App\Client::select('subscription_ends_at')
        ->groupBy('subscription_ends_at')
        ->get();

    $data_now = Carbon::now();

    foreach($date_expired as $users ){
        // $date_expired + 5 days

        if($date_expired > $data_now){
            //Send e-mail
        }
    }
}

【问题讨论】:

    标签: php sql laravel


    【解决方案1】:

    您应该使用whereDate() 将比较作为查询的一部分。在您的情况下,在 PHP 端过滤此数据没有任何好处:

    $now = Carbon::now()->addDays(5);
    
    $users =\App\Client::select('subscription_ends_at')
        ->groupBy('subscription_ends_at')
        ->whereDate('date_expired', '>', $now->toDateString()), 
        ->get();
    

    有关 Eloquent where 子句 here 的文档。

    编辑

    你的查询对我来说是错误的。使用groupBy() 将使其仅返回一小部分客户,将同一天到期的客户分组到一个条目中。这会破坏发送通知的目的,因为不是每个人都会收到通知,所以我宁愿完全删除 groupBy()

    【讨论】:

    • 太棒了!谢谢!
    【解决方案2】:

    使用addDays() 添加天数:

    Carbon::now()->addDays(5);
    

    此外,将其添加到查询中而不是加载所有数据和过滤器集合总是一个好主意:

    ->where('subscription_ends_at', '>', Carbon::now()->addDays(5))
    

    如果您将 subscription_ends_at 添加到 $dates 属性,这将起作用。

    【讨论】:

      猜你喜欢
      • 2018-07-24
      • 2017-05-31
      • 2016-09-20
      • 2010-10-26
      • 1970-01-01
      • 2018-03-24
      • 2012-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多