在 Laravel 5 中使用碳日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29668375/
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 11:21:56  来源:igfitidea点击:

Working with Carbon dates in Laravel 5

phplaravellaravel-5php-carbon

提问by Richie

I want to fetch tasks from my database that are starting at different times. i.e Starting Today, Tomorrow, Next Week and Next Month. Am trying to write scope in my model to handle that but I don't really know how to do it.

我想从我的数据库中获取在不同时间开始的任务。即从今天、明天、下周和下个月开始。我试图在我的模型中编写范围来处理这个问题,但我真的不知道该怎么做。

Here are my scope methods

这是我的范围方法

/**
 * @param $query
 * @return mixed
 */
public function scopeToday($query)
{
    return $query->where('start_at','=', Carbon::now());
}

/**
 * @param $query
 * @return mixed
 */
public function scopeTomorrow($query)
{
    return $query->where('start_at','=', Carbon::now()->addDay(1));
}

/**
 * @param $query
 * @return mixed
 */
public function scopeNextWeek($query)
{
    return $query->whereRaw('start_at = ?', [Carbon::now()->addWeek()]);
}

/**
 * @param $query
 * @return mixed
 */
public function scopeNextMonth($query)
{
    return $query->where('start_at','=', Carbon::now()->addMonth(1));
}

Any one with a clue why the above ain't working?

任何人都知道为什么上述方法不起作用?

Note: start_at is already a Carbon instance.

注意: start_at 已经是一个 Carbon 实例。

回答by mininoz

I guess you start_atfield is datetime type. And this might cause the problem on comparing date.

我猜你的start_at领域是datetime type. 这可能会导致比较日期的问题。

You need to convert datetimeto dateonly and use Carbon::today()instead of Carbon::now().

您需要转换datetimedateonly 并使用Carbon::today()而不是Carbon::now().

public function scopeToday($query)
{
    return $query->where( DB::raw('DATE(created_at)') ,'=', Carbon::today());
}


This shows the different between Carbon::today()and Carbon::now()

这显示了Carbon::today()Carbon::now()

$now = Carbon::now();
echo $now;                               // 2015-03-26 00:36:47
$today = Carbon::today();
echo $today;                             // 2015-03-26 00:00:00

source: http://carbon.nesbot.com/docs/#api-instantiation

来源:http: //carbon.nesbot.com/docs/#api-instantiation