Laravel Carbon addMinutes 不起作用的地方

Laravel where with Carbon addMinutes not working

我有一个 table 表示事件,每个事件都有一个通知期,例如如果当前距离活动开始时间不到 24 小时,您将无法预订该活动。

我正在尝试为此创建一个 'bookable' 范围,但失败了。具体如下,'time'表示事件发生的时间(timestamp),'notice'表示通知时间,单位为分钟(整数),两者都是Events模型中的列。我发现 Laravel 没有读取 'notice' 变量,即将其视为 0。任何指导将不胜感激,谢谢。

public function scopeBookable($q) {
    $q->where('time','>',Carbon::now()->addMinutes('notice'))->orderBy('time','ASC')->get();
}

addMinutes() 方法需要一个整数而不是字符串。

范围选项

您可以将通知时间传递给范围。

// Controller
$notice = 60;
Events::bookable($notice);

// Model
public function scopeBookable($q, $notice=0) {
    $q->where('time','>',Carbon::now()->addMinutes($notice))->orderBy('time','ASC')-get();
}

Collection 选项

您始终可以在 SQL 中执行 self-join 并在子查询中检查 notice 的值。另一种选择是 return 过滤 eloquent collection.

public function scopeBookable() {
    return Events::all()->filter(function($event) {
        return $event->time > Carbon::now()->addMinutes($event->notice)
    });
}