我有一个UserController,它有index()方法,它应该由一个用户在大会中获得所有注册,对于每一个注册,都要获得大会的详细信息(标题和日期)。因此,可以在视图"users.index“中显示大会的名称、日期和大会中所有用户注册的日期。
大会表中有一个列"end_congress_date",如果"end_congress_date“还在过去,就意味着大会尚未结束,否则就意味着大会已经结束了。
但没有发挥作用,也没有结果出现。你知道为什么吗?
所以我的索引()就像:
class UserController extends Controller
{
public function index(){
$user = Auth::user();
$registrations = $user->registrations()->with('congress')->get();
return view('users.index', compact('user','registrations'));
}
}
"dd($registrations);
“显示:
Collection {#281 ▼
#items: array:17 [▼
0 => Registration {#287 ▶}
1 => Registration {#288 ▶}
2 => Registration {#289 ▶}
]
}
index.blade.php:
<ul class="list-group congresses-list" id="">
@foreach($registrations->where('congress_end_date', '<=', \Carbon\Carbon::now()) as $reg)
<li class="list-group-item">
<p class="font-size-sm"><i class="fa fa-calendar" aria-hidden="true"></i>
{{$reg->congress->congress_start_date->formatLocalized('%a, %b %d, %Y - %H:%M')}}</p>
<h5 class="card-title">{{$reg->congress->name}}</h5>
<p> Registration done in {{$reg->created_at}}</p>
</li>
@endforeach
</ul>
发布于 2018-05-05 01:42:50
我建议在Congress
模型上添加一两个助手方法,告诉您国会是否已经结束。我希望知道这在整个应用程序中是一个常见的需求。
class Congress
{
// other code
public function isFinished(): bool
{
return $this->congress_end_date < now();
}
}
(这要求您对模型进行$dates = ['congress_end_date', ...]
转换。)
然后,您可以在集合上使用filter()
方法检索已经完成(或相反)的Registrations
的所有Congress
:
@foreach($registrations->filter(function ($item) { return $item->congress->isFinished(); }) as $reg)
// do something with the registrations of finished congresses
@endforeach
可选:只有当您不需要所有注册,而只需要完成注册时,才可以选择
如果您不打算使用$registrations
中的所有项目,而只使用那些已完成国会的项目,我建议您只获取所需的项目。您可以在您的控制器中通过交换进行此操作。
$registrations = $user->registrations()->with('congress')->get();
赞成
$registrations = $user->registrations()
->with('congress')
->whereHas(['congress' => function ($query) {
$query->where('congress_end_date', '<', now());
}])
->get();
然后,您可以在视图中简单地迭代它们,而无需在此之前进行过滤:
@foreach($registrations as $reg)
// ...
@endforeach
发布于 2018-05-05 01:18:05
问题是,您正在尝试对不存在的内容执行循环:
@foreach($registrations->where('congress_end_date', '<=', \Carbon\Carbon::now()) as $reg)
congress_end_date
字段不存在于注册对象上,它存在于关系:国会。因此,如果检查(如果日期少于现在)将失败100%的时间。因此..。没有注册将显示在users.index页面。
您有几个选项,您可以通过国会从DB中提取(假设您有返回到注册的关系),或者可能最简单的方法是像您拥有的那样在$registrations上循环,但是从foreach循环中删除日期检查,并在下面的国会模型上添加一个if检查。类似这样的事情(假设国会关系对许多人来说并不多):
@foreach($registrations as $registration)
if($registration->congress->congress_end_date < \Carbon\Carbon::now()))
// do what you want with the congress model that hasn't ended yet here
希望这能有所帮助
https://stackoverflow.com/questions/50184165
复制相似问题