我的控制器中的foraech循环有问题。
那是我的代码:
$appointments = Appointment::with('user')
->with('service')
->whereDate('scheduled_on', '>=', Carbon::today()->toDateString())
->orderBy('scheduled_on', 'asc');
Debugbar::info('$appointments count()='.$appointments->count());
if($appointments->count()) {
Debugbar::info('pos 1');
foreach ($appointments as $appointment) {
Debugbar::info('pos 2'); //not printed
}
}
return view('admin.appointments.index', ['appointments' => $appointments->paginate()]);
这就是我在调试栏中看到的内容:
$appointments count()=1
pos 1
因此,$ appointments有一个元素(第一个日志),但是我无法在其上循环。 在查看文件中,我使用
@foreach($appointments as $appointment)
在网格中显示我的结果,并且效果很好。
答案 0 :(得分:2)
您实际上并没有从查询中获取数据。
这部分创建一个查询生成器对象,并通过查询准备它:
$appointments = Appointment::with('user')
->with('service')
->whereDate('scheduled_on', '>=', Carbon::today()->toDateString())
->orderBy('scheduled_on', 'asc');
然后您执行$appointments->count()
来执行查询:
select COUNT(*) from `appointements` where date(`scheduled_on`) >= ? order by `scheduled_on` asc
这将为您提供正确数量的结果,而不是实际结果。
当您进入视图时,实际上执行了{strong>会执行查询的$appointments->paginate()
。但是,当您尝试循环查询构建器对象时。该迭代没有任何实际意义,很可能什么也没有发生。
如果要遍历控制器中的数据,可以执行以下操作:
foreach ($appointments->get() as $appointment) {
Debugbar::info('pos 2');
}