简体   繁体   中英

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('Date(created_at) = CURDATE()')->get();

I wonder if there is an easier, proper way to do this with 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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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