[英]Laravel Carbon, querying database where a field date is 2 weeks less than itself
我有一個選舉模型,在這里我試圖編寫一個查詢,向我顯示特定結果。
這個想法很簡單:
選舉的starting_date
例如為15/10/2018。
我需要查詢以顯示將在接下來的2周內開始的所有elections
。
我的意思是,對於這種情況,今天是01/10/2018,所以我需要所有從01/10/2018 - 15/10/2018
開始的選舉。
因此,我嘗試編寫如下內容:
public function notificationBeforeCollection() {
return $this->activeElections()
->where('start_collection', '>=', Carbon::now()
->subDays(14)->format('Y-m-d'))
->where('start_collection', '<', Carbon::now()
->format('Y-m-d'));
}
但是它不起作用,並且通過將starting_date
與今天進行比較看起來似乎不起作用。 看來我需要寫一些類似的東西:
where('starting_date', '>=', 'starting_date'->subDays(14);
如果我是對的,有沒有一種方法可以對查詢生成器中的字段使用Carbon
?
您的實際查詢正在尋找14天前開始的所有選舉。
您需要執行以下操作:
return $this->activeElections()->where('start_collection', '>', Carbon::today())
->where('start_collection', '<=' Carbon::today()->addDays(14));
從明天開始兩周的“選舉”
// using 'Carbon'
$start_date = Carbon::now()->addDay()->format('Y-m-d');
$end_date = Carbon::now()->addDays(14)->format('Y-m-d');
public function notificationBeforeCollection() {
return $this->activeElections()->whereBetween(
'start_collection', [$start_date, $end_date]
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.