我正在尝试根据Laravel中的年龄进行搜索查询。但是,当我尝试在两个日期之间进行查询时,我得不到任何结果。我的代码如下:
$today = Carbon::today();
$age_from = $today->subYears($request->age_from)->toDateString();
$age_to = $today->subYears($request->age_to)->toDateString();
$users->whereBetween('birthday', [$age_from, $age_to]);
//Get matching users.
$users = $users->Paginate(self::paginate);
当我使用mySql()查看时,查询看起来正确,但出于某种原因,我没有得到任何结果。语法错误可能?错误地使用toDateString并比较MySQL的日期?
编辑: $ age_from的输出是:
Carbon @959558400 {#245 ▼
date: 2000-05-29 00:00:00.0 UTC (+00:00)
}
$ age_to的输出是:
Carbon @-302745600 {#245 ▼
date: 1960-05-29 00:00:00.0 UTC (+00:00)
}
答案 0 :(得分:1)
原因是你正在改变$today
对象两次。如果您选中,$age_from
与第3行后的$age_to
具有相同的值。
你应该写:
$today = Carbon::today();
$age_from = $today->copy()->subYears($request->age_from);
$age_to = $today->copy()->subYears($request->age_to);
或只是
$age_from = Carbon::today()->subYears($request->age_from);
$age_to = Carbon::today()->subYears($request->age_to);
答案 1 :(得分:0)
归功于所有人,尤其是@skovmand和@Jonas Staudenmeir帮助我;我通过促进@skovmand的代码解决了这个问题,更重要的是(和我这边的愚蠢),日期应该交换,所以代替[$ age_from,$ age_to],它是[$ age_to,$ age_from],作为$ age_to显然是开始日期。但谢谢,伙计们! ^ _ ^