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

问题描述

我试图让我的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:

Psudo SQL:

Psudo 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 /雄辩中有更好的方法?

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);
});


推荐答案

您可以链接 直接,不含 function(q)。 laravel中还有一个很好的日期处理包,称为。所以你可以这样做:

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();

只需确定您需要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.

编辑:
As ,你可以这样做:

As Joel said, you could do:

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

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