2016-11-11 60 views
0

用一個查詢獲取第三個表數據的最佳方法是什麼?使用laravel雄辯提取數據表中的數據透視表一個查詢

User : id | name  
Event : id | user_id 
Likes : id | user_id | event_id 

Here is my Eloquent Query 

$events = Event::with('likes','users')->get(); 

return view('events',compact('events')); 

In views i am iterating over all events like this, 
User has multiple events as well as multiple likes in relation model. 


@foreach($events as $event) 

{{ $event->name }} 
{{ $like_id }} //show like id if it is liked by the user 

    // I have to execute another loop only to check if it is liked or not 
     @foreach($row->likes as $like) 

      @if(Auth::id() == $like->user_id) 
        Liked 
      @endif 
     @endforeach 

@endforeach 

現在,我需要檢查,如果登錄用戶已經很喜歡這個活動還是不是? 以及所有事件是否被喜歡?

回答

0

你可以爲嘗試:

@foreach($events as $event) 

    {{ $event->name }} 
    {{ $event->likes->count() }} 

    @if($event->likes->contains('user_id', Auth::id())) 
     Liked 
    @endif 

@endforeach 
相關問題