使用一个查询获取第三个表数据的最佳方法是什么。
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 :(得分:0)
您可以尝试:
@foreach($events as $event)
{{ $event->name }}
{{ $event->likes->count() }}
@if($event->likes->contains('user_id', Auth::id()))
Liked
@endif
@endforeach