Laravel Collection Date comparison

后端 未结 1 2006
忘了有多久
忘了有多久 2021-01-04 02:04

Alright so I have been looking for hours for an answer but can\'t seem to find one. I have an array of \"orders\" all for different dates. I get all of the orders for this w

1条回答
  •  孤城傲影
    2021-01-04 02:17

    Note: This answer is specific to Laravel <= 5.2. Laravel 5.3 updated the where() method on the Collection to match the query builder, so it now accepts an operator.


    As you state in your question, $dinnerOrders is a Collection, not a query. The where() method on the Collection works a little differently.

    For Collections, the where() method does not accept an operator. It only does equality comparisons. The first parameter is the key, the second is the value, and the third is a boolean to flag a loose comparison (==) vs a strict comparison (===).

    What you're looking for is the filter() method. You pass in a Closure that does your date comparison. If the Closure returns true, the item stays in the Collection. If it returns false, the item is removed from the Collection. Something like this (just an example, the logic may need to be tweaked):

    $dinnerOrders = $dinnerOrders->filter(function ($item) use ($date) {
        return (data_get($item, 'date') > $date) && (data_get($item, 'date') < $date->endOfDay());
    });
    

    Post Question Edit

    Based on the code provided in your edit, I'm guessing that a restaurant hasMany dinners, and a dinner hasMany orders. If this is correct, you can setup a relationship stating that a restaurant hasMany orders through dinners:

    Restaurant.php:

    public function orders() {
        // restaurant has many orders through dinners
        $this->hasManyThrough('App\Order', 'App\Dinner');
    }
    

    With this relationship setup, you could then get your information using the query builder:

    $dinnerOrders = $restaurant->orders()->where('date','>',$date)->where('date','<', $date->endOfDay())->get();
    

    0 讨论(0)
提交回复
热议问题