简体   繁体   English

从Laravel中的数据库获取特定的日期范围

[英]Getting specific date ranges from database in Laravel

I need to get results from a DB divided by dates such as today, yesterday, this week, last week, etc. 我需要从数据库中获得除以日期的结果,例如今天,昨天,本周,上周等。

I can easily do this with whereRaw and some SQL: 我可以使用whereRaw和一些SQL轻松做到这一点:

whereRaw('Date(created_at) = CURDATE()')->get();

I wonder if there is an easier, proper way to do this with Eloquent. 我想知道是否有一种更容易,正确的方法来使用Eloquent。

You could create a scope for a particular class like this: 您可以为特定类创建范围,如下所示:

public function scopeYourQuery($query, $user) {
    return $query->where('user_id', $user->id)->orderBy('created_at', 'desc')->first();
}

This just gets the first item of a descending ordered list ordered by created_at date per user. 这只是获取按用户的created_at日期排序的降序列表的第一项。

If you wanted something that was between date ranges? 如果您想要介于日期范围之间的值? You just pass in your date and extend it a bit with some PHP, maybe something like this would work: 您只需传递您的日期,然后使用一些PHP对其进行扩展,也许像这样工作即可:

public function scopeSomeDateQuery($query, $fetch_date, $user)
{
    //clone the users chosen month - so we can make the range until the following month
    $also_fetch_date = clone $fetch_date;
    $next_month = $also_fetch_date->addMonth();
    $next_month = $next_month->format('Y-m-d');
    $fetch_date = $fetch_date->format('Y-m-d');
    //return the query for the monthname
    return $query->orderBy('created_date')->where('created_date', '>=', $fetch_date)->where('created_date', '<', $next_month)->where('user_id', $user->id);
}

This would look in a monthly range (per user) to get an ordered list of items with a created_date in that range. 这将在每月范围(每位用户)中查找,以获取该范围内created_date的项目的有序列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM