I have a table, where a date column exists. We work with date ranges, that is, if I have a row with the date 2022-10-10, and the next one is 2022-10-15. It means that the data of the first row will also be taken for the intermediate days (10- 11-12-13-14).
The problem I have is that I don't know how to perform the query correctly. If the user selects a range of days, it should fetch the rows belonging to that range.
For example, if a user selects from 2022-10-12, to 15, he should collect the two commented rows, the one from day 10 and the one from day 15. But if the range is from 10 to 12, he should only have the row of day 10 (same as if user select from 12 to 13).
Example of table:
ID range_date data_id price
=== ======= ======= =======
1 2022-10-07 3 10
2 2022-10-10 5 50
3 2022-10-15 5 20
4 2022-10-16 3 40
... ... ...
EDIT for add some examples:
-With date from 2022-10-10 to 2022-10-12 -> return line 2
-With date from 2022-10-11 to 2022-10-13 -> return line 2
-With date from 2022-10-9 to 2022-10-15 -> return lines 1,2,3
-With date from 2022-10-9 to 2022-10-9 -> return line 1
CodePudding user response:
Lets suppose start and end filter date as,
$startDate = Carbon::parse($request->startDate)->startOfDay();
$endDate = Carbon::parse($request->endDate)->endOfDay();
$fitlerdData = Table::where(function($query) use($startDate, $endDate){
$query->where('date', '>=', $startDate)
->where('date', '<=', $endDate);
})->get();
CodePudding user response:
You should use the whereBetween()
method:
// $start = 2022-10-12;
// $end = 2022-10-15;
ModelName::whereBetween('date', [$start, $end])->get();