Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

eloquent - 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  

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.

I have found whereBetween clauses in Laravel documentation, but I do not have an idea to use it correctly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you can use Carbon then this code will work fine for you.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...