[英]Show post comments with relationship - Laravel
Hi I am new to Laravel and I and trying to create a relationship bewteen my posts and post comments.嗨,我是 Laravel 的新手,我试图在我的帖子和评论之间建立一种关系。
I want to show all comments on a post with the same post_id as the posts id.我想显示帖子 ID 与帖子 ID 相同的帖子的所有评论。 I think it should look something like this.
我认为它应该看起来像这样。 But I can not get it to work.
但我无法让它工作。 Any suggestions ?
有什么建议 ?
In the App\\BlogComments.php在 App\\BlogComments.php
public function posts(){
return $this->belongsTo('App\Post');
}
In the App\\Post.php在 App\\Post.php
public function BlogComments(){
return $this->hasMany('App\BlogComments');
}
In the BlogCommentsController:在 BlogCommentsController 中:
public function getComment($id)
{
$post = Post::find($id);
return $blogcomments->with('posts', $post->blogcomments);
}
In the posts/show.blade.php在帖子/show.blade.php
@foreach($blogcomments as $blogcomment)
{{$blogcomment->comment}}
@endforeach
In controller use this在控制器中使用这个
public function getComment($id)
{
$post = Post::with('blogcomments')->find($id);
return view('posts.show')->with('blogcomments', $post->blogcomments);
}
Or if only need blogComments that case或者如果只需要 blogComments 那种情况
public function getComment($id)
{
$blogcomments = BlogComments::where('post_id', $id)->get;
return view('posts.show')->with('blogcomments', $blogcomment);
}
Or you can do it this way或者你可以这样做
public function getComment($id)
{
$post = Post::with('blogcomments')->find($id);
return view('posts.show')->with('post', $post);
}
in view鉴于
@foreach($post->blogcomments as $blogcomment)
{{$blogcomment->comment}}
@endforeach
Edit: for comment issue编辑:评论问题
In BlogComments model define在 BlogComments 模型中定义
public function user() {
return $this->belongsTo('App\User');
}
And usage和用法
$post = Post::with('blogcomments.user')->find($id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.