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

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条)

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备