如果数据不存在,如何跳过关系?

时间:2019-05-10 13:55:57

标签: laravel eloquent laravel-blade

我有一个EventInvitation模型,它们之间有关系:一个事件可能有很多邀请。

我试图仅显示具有邀请的事件,否则,请跳过该事件。

我的Event模型:

class Event extends Model
{   
    public function invitations()
    {
        return $this->hasMany(Invitation::class, 'event_id') ?? [];   
}

如果关系不存在,我尝试使用?? [],返回空数组不起作用。

这是我的观点:

@if ($event->invitations != null)
    @foreach ($event->invitations as $event)
        <h5>{{ $event->email }}</h5>
    @endforeach
@else
    <h5>Not Found</h5>
@endif

它没有通过else语句。

else不存在时,我应该如何写它进入$event->invitations语句?

2 个答案:

答案 0 :(得分:3)

invitations()方法的返回结果是一个集合,因此,当您执行$event->invitations != null时,即使没有特定事件的邀请(空集合不同于true)。

我建议您根据情况检查集合的大小:

null

或者,快捷方式之一:

@if ($event->invitations->count())
    @foreach ($event->invitations as $event)
        <h5>{{ $event->email }}</h5>
    @endforeach
@else
    <h5>Not Found</h5>
@endif

甚至最短:

@empty ($event->invitations)
    <h5>Not Found</h5>
@else
    @foreach ($event->invitations as $event)
        <h5>{{ $event->email }}</h5>
    @endforeach
@endempty

答案 1 :(得分:2)

如果您只想获取带有邀请的活动,则可以使用has

NotFoundError Traceback (most recent call last)
NotFoundError: Key module/MobilenetV2/Conv/BatchNorm/beta not found in checkpoint
[[node save_2/RestoreV2 (defined at /usr/local/lib/python3.6/dist-packages/tensorflow_hub/native_module.py:451) ]]
相关问题