Get query results for date range

≡放荡痞女 提交于 2019-12-23 05:29:25

问题


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.


回答1:


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); 
    }); 


来源:https://stackoverflow.com/questions/27713474/get-query-results-for-date-range

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