Eloquent - 按天获取记录

Eloquent - Get records by day

我有一个代表某些事件的数据库记录列表。每个都有一个 start_time 列,其中包含以下格式的日期:2017-10-28 22:00:00。我希望能够使用 Laravel 获取列 start_time 是星期五的所有记录。像这样:

$fridayEvents = $q->whereDate('start_time', '=', isFriday());

但我很难用 Carbon 创建 isFriday()

whereDate() 只会检查日期,所以你不能用 whereDate()

检查日期

为了实现您的目标,您需要执行几个操作,我正在使用伪代码,因为我不知道您是如何查询的。

$records = Event::get();
$filteredArray = array();
foreach($records as $record){
    if(Carbon::parse($record->start_time)->dayOfWeek == Carbon::FRIDAY || Carbon::parse($record->start_time)->dayOfWeek == Carbon::SATURDAY){
        $fillteredArray[]= $record;
    }
}

希望对您有所帮助:)

MySQL(和其他 SQL)实现 WEEKDAY() 从日期中提取工作日的函数:

WEEKDAY(date)

Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).

mysql> SELECT WEEKDAY('2008-02-03 22:23:00');
        -> 6
mysql> SELECT WEEKDAY('2007-11-06');
        -> 1

所以你可以这样查询:

$q->whereRaw('WEEKDAY(your_table_name.start_date) = 4')

这种方式比使用 Carbon 直接在 PHP 上过滤结果更有效:

  • 您将使用比 Carbon 更快的原生数据库函数处理数据 PHP。
  • 只有相关数据会从数据库传输到 PHP,减少查询时间和内存使用量

要获得最佳性能,您需要创建一个列来存储工作日,这样您的数据库就可以使用索引来避免全table 扫描,从而为您提供最佳性能。

假设模型的 $casts 属性 正确地将列转换为日期,可以使用 Carbon 的 dayOfWeek 属性 轻松应用 filter method

/** @var \Illuminate\Support\Collection $events */
$fridays = $events->filter(
    fn ($v, $k) => $v->start_time->dayOfWeek === Carbon::FRIDAY
);

现在 $fridays 将只包含周五开始的那些事件。请注意, 中详述的数据库方法在您可以选择使用它的情况下仍然更有效,但这在从现有集合中提取子集时可能会有所帮助。

use Carbon\Carbon;

// this will return an array of events
$fridayEvents = $q->start_time;
// assign empty array variable
$dates = [];
//loop on the events 
foreach($fridayEvents as $event){
  // Use carbon to parse make sure it is a date not a string type then reformat it by using format() and the small 'l' inside the format returns the exact name for the day of that date
  // so if it is friday go and push into the array the entire event 
  if(Carbon::parse($event)->format('l') == 'Friday'){
    array_push($dates, $event);
  }
}
// die and dump the data after pushing into the $dates the events
dd($dates);