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 week, this should not be an issue, then I want to a tab for each day of the week.

到目前为止,我try 的是:

$dinnerOrders->where('date','>',$date)->where('date','<', $date->endOfDay())->sortBy('created_at');

其中$date是:

$dt = Carbon\Carbon::create()->startOfWeek();
Carbon\Carbon::setTestNow($dt);
$date = new Carbon\Carbon('this ' . $day);

和$DinnerOrders勉强度日:

$dinnerOrders = collect([]);
foreach($restaurant->dinners as $dinner) {
    foreach($dinner->orders as $order) {
        $dinnerOrders[$order->id] = $order;
    }
 }

日期看起来是正确的,而且它是用SQL写的.这不起作用是因为$dinnerOrders是一个集合吗?

我得到的是什么,也就是一个空集,尽管它在MySQL终端上工作.

So what I'm asking is perhaps, can you do a date comparison on a collection? If so, how?

推荐答案

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.

对于集合,where()方法不接受运算符.它只做平等比较.第一个参数是键,第二个是值,第三个是布尔值,用于标记松散比较(==)与严格比较(==).

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());
});

发布问题编辑

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');
}

设置此关系后,您可以使用查询构建器获取信息:

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

Laravel相关问答推荐

Laravel:如何从不断更新的Controller中分页数据

在Laravel Sail Docker环境中的PHPMyAdmin中出现`Out of Memory‘错误

spatie 包 laravel-tags 在迁移中没有 down() 函数是有原因的吗

Laravel | 使用select查询

Laravel 错误ReflectionException-类 App\Http\Kernel 不存在

插入重复键时,laravel eloquent 忽略错误

Laravel 合集日期比较

Laravel 5 - 没有重叠的任务计划不起作用

从 sqlite DB 登录 Laravel,得到PDOException 找不到驱动程序

如何在 Eloquent 上设置条件关系

如何在中间件 Laravel 中获取请求的控制器和操作的名称

在 Laravel 5.4 中将中间件应用于除 `setup/*` 之外的所有路由

413请求实体在laravel homestead for windows中太大的nginx服务器

Laravel 5.2 身份验证不起作用

Laravel 5 干预中的图像验证

Laravel 5.1-5.8 中以前的路由名称

在 Laravel 中按用户名查找用户

如何从 Laravel 中的资源中获取图像?

控制器中的laravel foreach循环

同一模型上的 Laravel 父/子关系