从关系中访问集合

时间:2017-07-21 08:57:10

标签: laravel laravel-5 eloquent

所以我有两张桌子。

DirtyEvent模型和Event模型。

我正在使用DirtyEvent检索Event哪个正常

在刀片中我有:

    @if (\Request::is('profile/event'))
      @foreach ($events as $event)
        @if (empty( $event->image ))
        <div class="card-header">
          <span class="card-title"><a href="{{ url('profile/event/details/' . $event->id) }}"> {{($event->title) }}</a></span>
        </div>
        @else
        <div class="card-image">
          <img class="img-responsive" src="{{ $event->image }}"></img>
          <span class="card-title"><a href="{{ url('profile/event/details/' . $event->id) }}"> {{($event->title) }}</a></span>
        </div>
        @endif
        <div class="card-content">
          <p><strong>Starts: </strong>@php echo ($startdate) @endphp - {{$event->startime }}</p>
        <br>
        @if ($startdate != $enddate)
          <p><strong>Ends: </strong>@php echo ($enddate) @endphp - {{$event->endtime }}</p>
        <br>
        @endif
        <p><strong>Description:</strong></p>
        <br>
        <p>{{$event->description }}</p>
        </div>

        <div class="card-action">
          <a href="{{ url('profile/event/edit/' . $event->id) }}"><i class="fa fa-pencil-square-o fa-2x" aria-hidden="true"></i></a>
          <form method="POST" action={{ url('events/delete/' . $event->id) }}>
            {{ method_field('PATCH') }}
            {{ csrf_field() }}
            <button type="submit" class="delete" style="border:none;"><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></button>
          </form>
        </div>
      @foreach ($events->publicevents as $eventss)
      {{dd($events)}}
      @endforeach
      @endforeach

然而dd($ events)给了我:

DirtyEvent Collection -> relations -> publicevents -> Event collection

但是,据说当前的收藏中不存在publicevents。

控制器

public function index()
{
    $id = Auth::id();
    $events = DirtyEvent::where('user_id', $id)
        ->with('publicevents')
        ->get();
    return view('events.viewEvent', compact('events'));
}

模型

public function publicevents()
{
    return $this->hasMany('App\Event', 'event_id');
}

enter image description here

1 个答案:

答案 0 :(得分:1)

我猜不是所有脏事件对象都有事件。因此,请先使用empty()isEmpty()count()

进行检查
@if (!empty($event->publicevents))
    @foreach ($event->publicevents as $eventss)
        {{ $eventss->id }}
    @endforeach
@endif

<强>更新

应该是$event->publicevents,而不是$events->publicevetns