简体   繁体   中英

Get query results for date range

I have the following query:

    $input_datestart = date("Y-m-d", strtotime($data["date_start"]));
    $input_dateend = date("Y-m-d", strtotime($data["date_end"]));

    //Calculate the recurrent dates 
    $query = $query->join('events_dates_recurrent', 'events.id', '=', 'events_dates_recurrent.event_id')
        ->whereRaw("ABS(DATEDIFF('" . $input_datestart . "', CAST(events_dates_recurrent.start_date AS DATE)) % events_dates_recurrent.repeat_interval) = 0");             

For a single day, I get the desired result now, which is to get recurrent events from my database for a given start_date.
When a date range is given however (ie. start AND end date), I'm unsure about how to get all results in a single query while avoiding a loop, taken into account that the recurrent events are still to be fetched.

Any suggestions?

Edit : The table structure is rather simple:

Table events_dates_recurrent :

event_id  |  start_date  |  end_date  |  repeat_interval 

Where event id is being linked to the table events with an inner join.
I need to retrieve all recurrent events within a given date range.
The end_date from the 'events_dates_recurrent' table can be ignored for now, perhaps this may serve a purpose later on, but it isn't strictly required for this query.

I am not particularly satisfied with this solution, but it does what it is supposed to do: What I basically do is loop through the input date interval and create a dynamic query string.
My application always limits the requested date / time interval to @maximum 1 month, so the query string should never exceed the max string limit.
I am not 100% about the performance though, we will see how that works out.

//Calculate the recurrent dates 
$query = $query->join('events_dates_recurrent', 'events.id', '=', 'events_dates_recurrent.event_id')
    ->where(function($join) use ($input_date_start, $input_date_end) { 
        //Create a dynamic query to get all recurrent dates within the input time interval 
        $query_string = "ABS(DATEDIFF('" . $input_date_start . "', CAST(events_dates_recurrent.start_date AS DATE)) % events_dates_recurrent.repeat_interval) = 0"; 
        $temp_date_start = $input_date_start; 

        while(strtotime($temp_date_start) <= strtotime($input_date_end)){ 
            $temp_date_start = date('Y-m-d',strtotime($temp_date_start . " +1 day")); 
            //Create a raw query string 
            $query_string = $query_string . " OR ABS(DATEDIFF('" . $temp_date_start . "', CAST(events_dates_recurrent.start_date AS DATE)) % events_dates_recurrent.repeat_interval) = 0"; 
        } 
        $join->whereRaw($query_string); 
    }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM