Laravel 在哪里使用 Carbon addMinutes 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44227007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:03:13  来源:igfitidea点击:

Laravel where with Carbon addMinutes not working

phplaravellaravel-5php-carbon

提问by user6122500

I have a table representing events, each of which has a notice period, e.g. you can't book the event if it's currently less than 24 hours before the event.

我有一个代表事件的表,每个表都有一个通知期,例如,如果当前距离事件发生前不到 24 小时,则您无法预订该事件。

I'm trying to create a 'bookable' scope for this, but am failing. Specifically, in the below, 'time' represents the time of the event (timestamp), and 'notice' the notice period, in minutes (integer), both of which are columns in the Events model. What I've found is that Laravel is not reading the 'notice' variable, i.e. treating it as 0. Any guidance would be appreciated, thanks.

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

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

回答by Dov Benyomin Sohacheski

The addMinutes()method expects an integer not a string.

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

Scope Option

范围选项

You can pass the noticetime through to the scope.

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

// 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 Option

收藏选项

You can always execute a self-join in SQL and check the value of noticein a subquery. Another option is to return a filtered eloquent collection.

您始终可以在 SQL 中执行自联接并检查notice子查询中的值。另一种选择是返回过滤后的 eloquent 集合。

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