Laravel如何检查日期是否在两个日期之间。

11

我想检查今天的日期是否在数据库中存储的两个日期之间。现在我使用laravel eloquent来实现这一点:

 return Set::where('type', $type)
            ->where('active_from', '<=', date("Y-m-d"))
            ->where('active_until', '>=', date("Y-m-d"))
            ->first();

这是否正确?


它是否返回了您所预期的结果? - WillardSolutions
1个回答

20

假设active_fromactive_until都只包含日期,那么这是正确的。但是如果它们包含带有时间的日期,你应该使用whereDate而不是where,如下所示:

return Set::where('type', $type)
            ->whereDate('active_from', '<=', date("Y-m-d"))
            ->whereDate('active_until', '>=', date("Y-m-d"))
            ->first();

此外,从代码来看,我相信你应该反过来使用运算符:active_from 应该是 >=,而 active_until 应该是 <=


如果数据库中的示例active_from和active_until设置为varchar,这是否有效? - Vincent Dapiton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接