Laravel $q->where() 日期之间 [英] Laravel $q->where() between dates

查看:59
本文介绍了Laravel $q->where() 日期之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让我的 cron 只接收将在未来 7 天内重复/续订的项目,以发送提醒电子邮件.我刚刚发现我的逻辑不太行.

I am trying to get my cron to only get Projects that are due to recur/renew in the next 7 days to send out reminder emails. I've just found out my logic doesn't quite work.

我目前有查询:

$projects = Project::where(function($q){
    $q->where('recur_at', '>', date("Y-m-d H:i:s", time() - 604800));
    $q->where('status', '<', 5);
    $q->where('recur_cancelled', '=', 0);
});

然而,我意识到我需要做的是:

However, I realized what I need to do is something like:

伪 SQL:

SELECT * FROM projects WHERE recur_at > recur_at - '7 days' AND /* Other status + recurr_cancelled stuff) */

我将如何在 Laravel 4 中执行此操作,并且使用 DATETIME 数据类型,我只使用时间戳完成了此类操作.

How would I do this in Laravel 4, and using the DATETIME datatype, I've only done this sort of thing using timestamps.

更新:

在使用以下代码后设法解决了这个问题,Stackoverflow 还可以帮助您提取一些代码并脱离上下文查看它们.

Managed to solve this after using the following code, Stackoverflow also helps when you can pull bits of code and look at them out of context.

$projects = Project::where(function($q){
    $q->where(DB::raw('recur_at BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()'));
    $q->where('status', '<', 5);
    $q->where('recur_cancelled', '=', 0);
});

更新的问题:在 Laravel/Eloquent 中是否有更好的方法来做到这一点?

Updated Question: Is there better way to do this in Laravel/Eloquent?

更新 2:

经过进一步测试,第一个解决方案最终不正确,我现在已经解决并测试了以下解决方案:

The first resolution ended up not been right after further testing, I have now resolved and tested the following solution:

$projects = Project::where(function($q){
    $q->where('recur_at', '<=', Carbon::now()->addWeek());
    $q->where('recur_at', '!=', "0000-00-00 00:00:00");
    $q->where('status', '<', 5);
    $q->where('recur_cancelled', '=', 0);
});

推荐答案

您可以直接链接您的 where,无需 function(q).Laravel 中还有一个不错的日期处理包,称为 Carbon.所以你可以这样做:

You can chain your wheres directly, without function(q). There's also a nice date handling package in laravel, called Carbon. So you could do something like:

$projects = Project::where('recur_at', '>', Carbon::now())
    ->where('recur_at', '<', Carbon::now()->addWeek())
    ->where('status', '<', 5)
    ->where('recur_cancelled', '=', 0)
    ->get();

只要确保你在 composer 中需要 Carbon 并且你正在使用 Carbon 命名空间(使用 Carbon\Carbon;),它应该可以工作.

Just make sure you require Carbon in composer and you're using Carbon namespace (use Carbon\Carbon;) and it should work.

正如乔尔所说,你可以这样做:

$projects = Project::whereBetween('recur_at', array(Carbon::now(), Carbon::now()->addWeek()))
    ->where('status', '<', 5)
    ->where('recur_cancelled', '=', 0)
    ->get();

这篇关于Laravel $q->where() 日期之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆