首页  >  文章  >  数据库  >  如何使用 Laravel 的 `$q->where()` 查询日期之间的数据?

如何使用 Laravel 的 `$q->where()` 查询日期之间的数据?

Linda Hamilton
Linda Hamilton原创
2024-10-26 04:27:30635浏览

 How to Query Data Between Dates with Laravel's `$q->哪里()`? 
“ />在哪里()`?

Laravel 使用 $q->where() 进行“日期之间”查询

使用 Laravel 的 $q-> 检索指定日期范围内的数据;where() 方法,您可以采用多种方法。一种技术是利用闭包来链接多个 where 条件:

<code class="php">$projects = Project::where(function($q){
    $q->where('recur_at', '>', Carbon::now())
      ->where('recur_at', '<', Carbon::now()->addWeek())
      ->where('status', '<', 5)
      ->where('recur_cancelled', '=', 0);
});</code>

或者,您可以直接链接 where 条件而不使用闭包:

<code class="php">$projects = Project::where('recur_at', '>', Carbon::now())
    ->where('recur_at', '<', Carbon::now()->addWeek())
    ->where('status', '<', 5)
    ->where('recur_cancelled', '=', 0);</code>

Laravel 的 whereBetween() 方法提供了一种简洁的方法来处理日期范围:

<code class="php">$projects = Project::whereBetween('recur_at', [Carbon::now(), Carbon::now()->addWeek()])
    ->where('status', '<', 5)
    ->where('recur_cancelled', '=', 0);</code>

请记住在 Composer 中需要 Carbon 并利用 Carbon 命名空间以使这些解决方案正常运行。

以上是如何使用 Laravel 的 `$q->where()` 查询日期之间的数据?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn