简体   繁体   中英

Laravel eloquent where date is equal or greater than DateTime

I'm trying to fetch relational data from a model where the date column is higher or equal to the current time.

The date column is formated as this: Ymd H:i:s

What I'm trying to do is to grab all rows where the Ymd H:i:s is in the future.

Example: lets assume the date is 2017-06-01 and the time is 09:00:00 Then i would like got all rows where the date is in the future, and the time is in the future.

Currently my code looks like this, and it's almost working but it doesn't grab the rows where the date is the current day.

public function customerCardFollowups() {
    return $this -> hasMany('App\CustomerCardFollowup', 'user_id') -> whereDate('date', '>', Carbon::now('Europe/Stockholm')) -> orderBy('date', 'asc') -> take(20);
}

What am I doing wrong? Thanks in advance.

听起来你需要使用>= ,例如:

->whereDate('date', '>=', Carbon::now('Europe/Stockholm'))

在这里你可以使用这个:

->where('date', '>=', date('Y-m-d'))

For Laravel's TestCases:

$this->assertDatabaseHas('my_table', [
    'name' => $name,
    [ 'updated_at', '>=', $updatedAt ] // $updatedAt is a Carbon object
]);

Using whereDate will compare the date only and ignore the time . So your solution will give the records that are at least dating one day later and the records that are in the same day but with later hours will not be included.

If you use >= as suggested you will get records starting from the current date and those ones who are even before the determined hour.

One solution for this is comparing using MySQL functions in whereRaw . In your code the condition for the date will be like this:

-> whereRaw("date > STR_TO_DATE(?, '%Y-%m-%d %H:%i:%s')" , Carbon::now('Europe/Stockholm')->format('Y-m-d H:i'));

In the code, I changed the format of Carbon date to match a specific format where you can use whatever format you want and put the same format in the STR_TO_DATE function.

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