【问题标题】:How to skip relationship if it data does not exist?如果数据不存在,如何跳过关系?
【发布时间】:2019-09-28 10:54:23
【问题描述】:

我有一个Event 和一个Invitation 模型,它们之间的关系是:一个活动可以有很多邀请。

我试图只显示有邀请的活动,如果没有,请跳过该活动。

我的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 语句。

$event-&gt;invitations 不存在时,我应该如何将其写入else 语句?

【问题讨论】:

  • @TimLewis 我认为?? [] 不会引起任何问题,它永远不会被调用。 $this-&gt;hasMany总是返回一些东西。

标签: laravel eloquent laravel-blade


【解决方案1】:

invitations()方法的返回结果是一个集合,所以当你做$event-&gt;invitations != null时,它总是true,即使没有特定事件的邀请(空集合不同于@ 987654324@).

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

@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

甚至最短:

@forelse ($event->invitations as $event)
    <h5>{{ $event->email }}</h5>
@empty
    <h5>Not Found</h5>
@endforelse

【讨论】:

    【解决方案2】:

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

    $events = Event::has('invitations')->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-09
      • 1970-01-01
      • 2020-04-02
      • 2020-05-23
      • 2021-11-10
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多