![](/img/trans.png)
[英]How to check given date period is between two dates in MySQL and PHP
[英]How to check if period between two dates intersects with array of years
我有一個 Laravel 項目。 我的 model 有字段時間戳“開始”和“結束”。 該請求有一個參數作為年份數組等: years = [2019, 2021, ...]
。
我想通過Model::where(...)
, Model::whereIn(...)
或所有與“年”參數相交的記錄來獲取。
例子:
如果years = [2019, 2021]
,我需要獲取start = "2018-01-01", end = "2019-12-31"
或start = "2018-01-01", end = "2025-12-31"
,但不是start = "2020-01-01", end = "2020-12-31"
。
我怎樣才能做到這一點?
下一個解決方案如何:
use Illuminate\Database\Eloquent\Builder;
$years = [2019, 2021];
Model::where(
static function (Builder $query) use ($years) {
foreach ($years as $year) {
$start = "{$year}-01-01";
$end = "{$year}-12-31";
$query->orWhereRaw("('{$start}' BETWEEN `start` AND '{$end}' OR `start` BETWEEN '{$start}' AND '{$end}')");
}
}
);
或者
use Illuminate\Database\Eloquent\Builder;
$years = [2019, 2021];
Model::where(
static function (Builder $query) use ($years) {
foreach ($years as $year) {
$query->orWhere(
static function (Builder $query) use ($year) {
$query->whereYear('start', $year)
->whereYear('end', $year);
}
);
}
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.