Laravel 5: Check if event date range is not already taken

拥有回忆 提交于 2019-12-10 10:05:10

问题


I'm creating calendar for few days events and the events can not overlap. But event can start/end when another event starts/ends.

In Laravel, in my event model table I am storing start and end date of events. How can I check before storing new event do database, if it is valid (is not overlapping with existing events, excluding margin/boundary days) ?

In advance thank You very much for Your help.


回答1:


You can use following code to get the correct counts for events booked between certain times:

$eventsCount = Events::where(function ($query) use ($startTime, $endTime) {
 $query->where(function ($query) use ($startTime, $endTime) {
    $query->where('start', '>=', $startTime)
            ->where('end', '<', $startTime);
    })
    ->orWhere(function ($query) use ($startTime, $endTime) {
        $query->where('start', '<', $endTime)
                ->where('end', '>=', $endTime);
    });
})->count();



回答2:


This is just some pseudocode since you don't provide any code or your model, but depending on how your table is set up, you should be able to do it like this. This will return any events where the new event's start time or end time falls between an existing event's start and end times. This will work if your times are timestamps, or DateTime columns.

 Events::where(DB::raw("? between start_time and end_time",$start))
      ->orWhere(DB::raw("? between start_time and end_time",$end))
      ->get();



回答3:


Use it for all variants intersections date ranges. It help for me

$rangeCount = TransferSchedule::where(function ($query) use ($from, $to) {
                $query->where(function ($query) use ($from, $to) {
                    $query->where('date_from', '<=', $from)
                        ->where('date_to', '>=', $from);
                })->orWhere(function ($query) use ($from, $to) {
                    $query->where('date_from', '<=', $to)
                        ->where('date_to', '>=', $to);
                })->orWhere(function ($query) use ($from, $to) {
                    $query->where('date_from', '>=', $from)
                        ->where('date_to', '<=', $to);
                });
            })->count();


来源:https://stackoverflow.com/questions/40245007/laravel-5-check-if-event-date-range-is-not-already-taken

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!