dty47696 2018-05-29 12:06
浏览 670
已采纳

whereBetween与日期不起作用

I'm trying to make a search query based on ages in Laravel. However, when I try to query between two dates, I get no results back. My code looks like:

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

The query looks right when I review with mySql(), but for some reason, I do not get any results. Syntax error maybe? Wrong use of toDateString and comparison of MySQL's date?

EDIT: The output of $age_from is:

Carbon @959558400 {#245 ▼
date: 2000-05-29 00:00:00.0 UTC (+00:00)
}

The output of $age_to is:

Carbon @-302745600 {#245 ▼
date: 1960-05-29 00:00:00.0 UTC (+00:00)
}
  • 写回答

2条回答 默认 最新

  • dsgdhtr_43654 2018-05-29 12:17
    关注

    The reason is that you are mutating the $today object twice. If you check, $age_from has the same value as $age_to after line 3.

    You should instead write:

    $today = Carbon::today();
    $age_from = $today->copy()->subYears($request->age_from);
    $age_to = $today->copy()->subYears($request->age_to);
    

    or simply

    $age_from = Carbon::today()->subYears($request->age_from);
    $age_to = Carbon::today()->subYears($request->age_to);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?