[英]How can I display posts' comment?
我应该为帖子提供 id 吗? Laravel 如何知道哪些评论属于哪个帖子?
这是我的 controller :
public function show($id){
$posts=Post::where('id',$id)->get();
return view('user',compact('posts'));
}
这是我的刀片:
@foreach($posts->comments as $comment)
<div class="comment-form">
<section class="post-body">
<p>{{ $comment->description }}</p> <!-- burda ilisdim -->
</section>
</div>
@endforeach
所以我建立了关于评论的多态关系。 但我不知道如何使用它。
更新
这是我的帖子 Model
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
}
您需要在model 后定义关系,如下所示:
public function comments()
{
return $this->hasMany(Comment::class);
}
然后你可以像这样访问:
@foreach($posts->comments as $comment) // $posts->comments will call your comments() function
{{ $comment->description }}
@endforeach
我可以看到你做错了什么。 请用以下代码替换您的代码:要获得单个帖子,您必须用 controller 中给出的代码替换代码
public function show($id){
$posts=Post::where('id',$id)->first();
return view('user',compact('posts'));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.