ChatGPT解决这个技术问题 Extra ChatGPT

如何使用 Laravel 和 Eloquent 在两个日期之间进行查询?

我正在尝试创建一个显示从特定日期到特定日期的报告的报告页面。这是我当前的代码:

$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', $now)->get();

这在普通 SQL 中的作用是 select * from table where reservation_from = $now

我在这里有这个查询,但我不知道如何将其转换为雄辩的查询。

SELECT * FROM table WHERE reservation_from BETWEEN '$from' AND '$to

如何将上面的代码转换为雄辩的查询?先感谢您。

reservation_from 中的日期格式是什么。您可以基于此使用碳值。
日期格式为 TIMESTAMP @AthiKrishnan
就像,Reservation::where('reservation_from', '>=', Carbon::createFromDate(1975, 5, 21);) ->where('reservation_from', '<=', Carbon::createFromDate(2015, 5, 21);)->get()

j
jeremykenedy

whereBetween 方法验证列的值是否介于两个值之间。

$from = date('2018-01-01');
$to = date('2018-05-02');

Reservation::whereBetween('reservation_from', [$from, $to])->get();

在某些情况下,您需要动态添加日期范围。根据 @Anovative 的评论,您可以这样做:

Reservation::all()->filter(function($item) {
  if (Carbon::now()->between($item->from, $item->to)) {
    return $item;
  }
});

如果您想添加更多条件,则可以使用 orWhereBetween。如果您想排除日期间隔,则可以使用 whereNotBetween

Reservation::whereBetween('reservation_from', [$from1, $to1])
  ->orWhereBetween('reservation_to', [$from2, $to2])
  ->whereNotBetween('reservation_to', [$from3, $to3])
  ->get();

其他有用的 where 子句:whereInwhereNotInwhereNullwhereNotNullwhereDatewhereMonthwhereDaywhereYearwhereTimewhereColumn whereExists、{ 12}。

Laravel docs about Where Clauses.


如果 $from$to 是属于模型的动态日期,将如何处理?因为有一个 effective_atexpires_at 字段,我想查询当前项目是否在该范围内。我尝试了使用 Carbon::now()->between( ... ) 的 if each(),但它仍然返回所有结果。
编辑我的上述评论:忽略 filter(),这成功了。 MyModel::all()->where('column', 'value')->filter(function ($item) { if (Carbon::now->between($item->effective_at, $item->expires_at)) { return $item; } })->first();
@Anovative 感谢您的有用评论。我会根据您的评论更新我的答案。
第二种方法有问题。它将所有记录从数据库加载到内存,然后只有它会执行过滤。
非常感谢你为我节省了很多时间!
t
tomloprod

如果您的字段是 datetime 而不是 date,则另一种选择(虽然它适用于两种情况):

$fromDate = "2016-10-01";
$toDate   = "2016-10-31";

$reservations = Reservation::whereRaw(
  "(reservation_from >= ? AND reservation_from <= ?)", 
  [
     $fromDate ." 00:00:00", 
     $toDate ." 23:59:59"
  ]
)->get();

从技术上讲,它不需要是 $toDate 。 “23:59.59.999”?
@stevepowell2000 这取决于您的数据库,在我的情况下,我们将日期以这种格式 'YYYY-MM-DD HH:MM:SS' 存储在 datetime mysql 字段中,没有微秒精度。相关信息:dev.mysql.com/doc/refman/8.0/en/datetime.html
好点。因此,如果它是一个日期时间或时间戳字段,我们可能会一直走到 23:59:59.999999 “一个日期时间或时间戳值可以包括一个尾随小数秒部分,精度高达微秒(6 位)。”
谢谢你一直帮助我完成我的任务!喜欢这个答案兄弟! :)-哈比
M
ManojKiran Appathurai

我已经创建了模型范围

有关范围的更多信息:

https://laravel.com/docs/eloquent#query-scopes

https://medium.com/@janaksan_/using-scope-with-laravel-7c80dd6a2c3d

代码:

   /**
     * Scope a query to only include the last n days records
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeWhereDateBetween($query,$fieldName,$fromDate,$todate)
    {
        return $query->whereDate($fieldName,'>=',$fromDate)->whereDate($fieldName,'<=',$todate);
    }

在控制器中,将碳库添加到顶部

use Carbon\Carbon;

从现在开始获取最近 10 天的记录

 $lastTenDaysRecord = ModelName::whereDateBetween('created_at',(new Carbon)->subDays(10)->startOfDay()->toDateString(),(new Carbon)->now()->endOfDay()->toDateString() )->get();

从现在开始获取最近 30 天的记录

 $lastThirtyDaysRecord = ModelName::whereDateBetween('created_at',(new Carbon)->subDays(30)->startOfDay()->toDateString(),(new Carbon)->now()->endOfDay()->toDateString() )->get();

WhereDateBetween 第二个参数需要是一个数组。
它只是模型的一个范围,它不是 Builder 方法
哦,是的,不知何故错过了。我的错:)
N
Nur Uddin

如果您想检查当前日期是否存在于 db 中的两个日期之间:=>这里查询将获取应用程序列表,如果员工的应用程序从和到日期存在于今天的日期。

$list=  (new LeaveApplication())
            ->whereDate('from','<=', $today)
            ->whereDate('to','>=', $today)
            ->get();

P
Pᴇʜ

以下应该有效:

$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', '>=', $now)
                           ->where('reservation_from', '<=', $to)
                           ->get();

A
ArtisanBay

尝试这个:

由于您是基于单个列值获取的,因此您可以同样简化查询:

$reservations = Reservation::whereBetween('reservation_from', array($from, $to))->get();

根据条件检索:laravel docs

希望这有帮助。


如果您想要一个从 2021 年 2 月 1 日到 2021 年 5 月 31 日的寄存器,并且这个寄存器是在 2021 年 5 月 31 日创建的,那么请小心,它不会起作用,在这种情况下,您应该使用这个:whereDate('created_at', '>=', $this->start_date) ->whereDate('created_at', '<=', $this->end_date) ->get()
Z
Zoe stands with Ukraine

如果您需要在 datetime 字段应该是这样的时间。

return $this->getModel()->whereBetween('created_at', [$dateStart." 00:00:00",$dateEnd." 23:59:59"])->get();

您好,欢迎来到 Stack Overflow。在回答已经有很多答案的问题时,请务必添加一些额外的见解,说明为什么您提供的回复是实质性的,而不是简单地呼应原始发帖人已经审查过的内容。这在“仅代码”的答案中尤其重要,例如您提供的答案。
I
Ismail

我遵循了其他贡献者提供的有价值的解决方案,并遇到了一个没有人解决的小问题。如果 reservation_from 是日期时间列,则它可能不会产生预期的结果,并且会丢失日期相同但时间高于 00:00:00 时间的所有记录。为了改进上面的代码,需要像这样进行一些小的调整。

$from = Carbon::parse();
$to = Carbon::parse();
$from = Carbon::parse('2018-01-01')->toDateTimeString();
//Include all the results that fall in $to date as well
$to = Carbon::parse('2018-05-02')
    ->addHours(23)
    ->addMinutes(59)
    ->addSeconds(59)
    ->toDateTimeString();
//Or $to can also be like so
$to = Carbon::parse('2018-05-02')
    ->addHours(24)
    ->toDateTimeString();
Reservation::whereBetween('reservation_from', [$from, $to])->get();

E
Excellent Lawrence

我知道这可能是一个老问题,但我发现自己不得不在 Laravel 5.7 应用程序中实现此功能。以下是我的工作。

 $articles = Articles::where("created_at",">", Carbon::now()->subMonths(3))->get();

您还需要使用碳

use Carbon\Carbon;

E
ESP-RAY

这是我的答案,谢谢Artisan Bay,我阅读了您的评论以使用wheredate()

有效

public function filterwallet($id,$start_date,$end_date){

$fetch = DB::table('tbl_wallet_transactions')
->whereDate('date_transaction', '>=', $start_date)                                 
->whereDate('date_transaction', '<=', $end_date)                                 
->get();

a
aimme

诀窍是改变它:

Reservation::whereBetween('reservation_from', [$from, $to])->get();

Reservation::whereBetween('reservation_from', ["$from", "$to"])->get();

因为日期必须是mysql中的字符串类型