我的评论模型与博客和酒店有变形关系,在这里我得到了所有用户对酒店的评论,现在我如何访问酒店详细信息,如名称、刀片中的描述?
$hotelComments = Comment::whereHasMorph(
'commentable',
Hotel::class,
)->whereUserId(Auth::id())->get();
叶片:
@foreach ($hotelComments as $hc)
<tr>
<td class="">{{ $hc->body }}</td>
<td class="">{{ $hc-> ??? hotel name ??? }}</td>
</tr>
@endforeach
博客和酒店 :
public function comments(){
return $this->morphMany(Comment::class, "commentable");
}
评论模型:
public function commentable(){
return $this->morphTo();
}
您可以在评论模型上使用属于关系,如下所示
public function hotel()
{
return $this->belongsTo(Hotel::class,'commentable_id');
}
在控制器中:
public function index(){
$comments = Comments::where('commentable_type','AppHotels')->with('hotel')->get();
foreach($comments as $comment){
dd($comment->hotel)
}
}