在Laravel中检索两个日期之间的数据 [英] Retrieve data between two dates in laravel
问题描述
我正在使用雄辩的查询从表中检索数据.表格列如下所示:
I am using an eloquent query to retrieve data from a table. The table columns look like this:
id started_at finished_at
1 2016-06-01 2016-06-30
2 2016-05-03 2016-05-28
我想做的是,给定$date
(例如:2016-06-18)并获取该行的数据,即$date
在at列和finished_at列之间.
What I want to do is, given a $date
(ex: 2016-06-18 ) and get the data of the row, that the $date
between started at and finished_at columns.
我在 Laravel文档中找到了whereBetween
子句,但是我确实没有正确使用它的想法.
I have found whereBetween
clauses in Laravel documentation, but I do not have an idea to use it correctly.
推荐答案
如果您可以使用Carbon,那么此代码对我来说效果很好.
If you can use Carbon then this code is working fine for me.
$dateS = new Carbon('first day of January 2016');
$dateE = new Carbon('first day of November 2016');
$result = ModelName::whereBetween('created_at', [$dateS->format('Y-m-d')." 00:00:00", $dateE->format('Y-m-d')." 23:59:59"])->get();
或者您可以通过使用DB::enableQueryLog();
和DB::getQueryLog();
函数(如
Or you can check the issue by debugging query using DB::enableQueryLog();
and DB::getQueryLog();
functions like
DB::enableQueryLog();
$dateS = new Carbon('first day of January 2016');
$dateE = new Carbon('first day of November 2016');
$result = ModelName::whereBetween('created_at', [$dateS->format('Y-m-d')." 00:00:00", $dateE->format('Y-m-d')." 23:59:59"])->get();
var_dump($result, DB::getQueryLog());
这篇关于在Laravel中检索两个日期之间的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!