Laravel Carbon,查询字段日期比其本身少 2 周的数据库
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));
从明天开始获得 'Elections' 两周的时间
// 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]
);
}
我有一个选举模型,我正在尝试编写一个查询来显示具体结果。
这个想法很简单:
选举 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));
从明天开始获得 'Elections' 两周的时间
// 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]
);
}