我需要在現有項目上實現某些事件的顯示。我無法更改數據庫結構。MySQL如何從年(參數),weekOfYear(參數),時間(數據庫)和dayofweek(數據庫)創建時間戳?
在我的控制器中,我通過(從ajax請求)時間戳,我需要顯示以前的8個事件。所以如果時間戳是(轉換)2017-12-12 00:00:00我需要在2017-12-12之前顯示8個事件,按照他們的時間命令DESC。
這是我的表是如何設置:
-calendarrepeat
-dayofweek // int 1-7; 1 = monday, 7 = sunday
-event_date_begin // date "2016-05-01" - indicates from which day the event recurrs every week (dayofweek)
-event_date_end // date "2017-05-02" - indicates until which day the event recurrs every week (dayofweek)
-event_hour_begin // time "11:00:00"
-event_hour_end // time "12:00:00"
我可以做我想做的事情與時間戳。我使用Carbon,因此獲得一年中的某一週,一年中的某一天或任何其他我需要的內容都不是問題。
僅供參考$fullTs
是我傳遞給控制器的時間戳。聯接部分工作正常。
我需要幫助的部分是:/* THIS PART has to be rewritten (it's COMPLETELY wrong at the moment) ! */
我需要生成從今年timestmap(作爲參數傳遞),WEEKOFYEAR(作爲參數傳遞),一週中的一天(從數據庫列)和時間(數據庫列)。我需要這樣的事,而不是(pseudoSQL):
->where(\DB::raw('THISTHINGY_TO_DATE($fullTs->year $fullTs->weekOfYear calendarrepeat.dayofweek calendarrepeat.event_hour_begin, "%Y %week-of-year %day-of-week %H:%i:%s), '<', $fullTs)))
這是我目前運行完整查詢(UNION的第一部分,第二個按預期工作):
$eventsRepeat = CalendarRepeat::join('calendarrepeat_translations', function ($j) use ($locale) {
$j->on('calendarrepeat.id', '=', 'calendarrepeat_translations.calendarrepeat_id')
->where('calendarrepeat_translations.locale', '=', $locale);
})
->orderBy('calendarrepeat.event_date_begin', $orderBy)
/* THIS PART has to be rewritten (it's COMPLETELY wrong at the moment) ! */
/* the STR_TO_DATE(..) part has to get date from a) week passed in $fullTs b) dayoftheweek written in calendarrepeat.dayoftheweek c) time written in calendarrepeat.event_hour_begin */
->where(\DB::raw("STR_TO_DATE(CONCAT(calendarrepeat.event_date_begin, ' ', calendarrepeat.event_hour_begin), '%Y-%m-%d %H:%i:%s')"), '<', $fullTs)
->where('event_date_begin', '>', $fullTs)
->where('event_date_end', '<', $fullTs)
->limit(8)
->select([
'calendarrepeat.event_date_begin as date', 'calendarrepeat.event_hour_begin as start',
'calendarrepeat.event_hour_end as end', 'calendarrepeat_translations.title as title', \DB::raw("CONCAT(calendarrepeat.event_date_begin, ' ', calendarrepeat.event_hour_begin) as date_whole") // This is also wrong
]);
這可能嗎?怎麼樣?有沒有更好的方式去做這件事?
另一件需要注意的事情是,在我們的DB 1 =星期一,7 =星期日,根據我的理解,這並不是列舉星期幾的常用方式。
在此先感謝。