场景: 数据库有有两个字段.开始时间,和结束时间,指定一个时间段(a,b),a表示开始时间,a表示结束时间。看数据库中有没有与(a,b)冲突的时间段,有的话就返回那条记录。
解析:两个时间段相当于两个集合,不过是有顺序的集合。两个时间段有交集细分有四种情况。用sql直接判断无交集的语句可能也有,但是目前没有想到,只想到有交集的语句,如果返回不为空则表明有交集,否则没有交集。
环境:Laravel 5.7
php7.1.16
mysql5.7
废话不多say,直接上代码:
public function checkRegionUse($start_time,$end_time){
$positionuse=Position_use::WhereBetween('start_time', [$start_time, $end_time])
->orWhereBetween('end_time', [$start_time, $end_time])
->orwhere('start_time','<',$start_time)
->where('end_time','>',$end_time)
->orwhere('start_time','>',$start_time)
->get();
if ($positionuse->isEmpty()){
return false;
}else{
return $positionuse;
}
}
这段代码主要解决4种情况
1.startTime > a AND startTime < b
2.startTime < a AND endTime > b
3.endTime > a AND endTime < b