我创建了一个帖子和评论应用程序。我正在尝试将评论链接到帖子的id
。我试图在Blade模板中使用PHP来执行此操作。我得到变量post_id
不存在的错误。我想使用Blade的@if
和@foreach
。问题似乎出现在@if
声明中。
这是我的HTML:
<div class="col-md-9">
<div class="row">
@foreach($posts as $post)
<div class="col-md-12 post" id="post{{ $post->id }}">
<div class="row">
<div class="col-md-12">
<h4>
{{ $post->title }}
</h4>
</div>
</div>
<div class="row">
<div class="col-md-12 post-header-line">
<span class="glyphicon glyphicon-user"></span> by <a href="#">{{ $post->user->firstName }} {{ $post->user->lastName }}</a> | <span class="glyphicon glyphicon-calendar">
</span> {{ $post->created_at }} | <span class="glyphicon glyphicon-comment"></span><a href="#">
3 Comments</a>
</div>
</div>
<div class="row post-content">
<div class="col-md-2">
<a href="#">
<img src="/images/random/postimg.jpg" alt="" class="img-responsive postImg">
</a>
</div>
<div class="col-md-10">
<p>
{{ $post->post }}
</p>
</div>
</div>
<div class="row add-comment">
<div class="form-group">
<input type="text" name="addComment" placeholder="Add your comment" class="form-control" v-model="comment">
</div>
<input id="addComment" type="submit" name="submitComment" value="Submit Comment" class="btn btn-default" v-on:click="submitComment" data-id="{{ $post->id }}">
</div>
@if($post->comment->post_id == $post->id)
@foreach($post->comment as $comment)
<div class="row">
<div class="col-md-12 mb-r">
<div class="card example-1 scrollbar-ripe-malinka">
<div class="card-body">
<h4 id="section1"><strong>By: {{ $comment->user->firstName }} {{ $comment->user->lastName }}</strong></h4>
<p>{{ $comment->comment }}</p>
</div>
</div>
</div>
</div>
@endforeach
@endif
</div>
@endforeach
</div>
</div>
这是我的PostController:
public function index(){
$posts = Post::with('comment', 'user')->orderBy('id', 'desc')->limit(20)->get();
return view('post.posts')->with('posts', $posts);
}
答案 0 :(得分:0)
您需要将post_id
添加到comments
表并使用以下关系:
public function comments()
{
return $this->hasMany(Comment::class);
}
然后您就可以加载相关评论了:
Post::with('comments', ....
迭代帖子及其评论:
@foreach ($posts as $post)
@foreach ($post->comments as $comment)
{{ $comment->content }}
@endforeach
@endforeach
答案 1 :(得分:0)
您不需要@if
声明,请将其删除。 $post->comment
是一个集合,这就是为什么你没有得到post_id
。如果您想查看,请在foreach
内查看。
@foreach($post->comment as $comment)
<div class="row">
<div class="col-md-12 mb-r">
<div class="card example-1 scrollbar-ripe-malinka">
<div class="card-body">
<h4 id="section1"><strong>By: {{ $comment->user->firstName }} {{ $comment->user->lastName }}</strong></h4>
<p>{{ $comment->comment }}</p>
</div>
</div>
</div>
</div>
@endforeach
答案 2 :(得分:0)
我认为如果你在Post模型和Comment模型(post table和comments table)之间创建关系,你的@if就没用了。我建议你检查相应的型号。
你的代码应该是这样的, post.php中
public function comments(){
return $this->morphMany('App\Comments','commentable');
}
Comment.php
public function commentable(){
return $this->morphTo();
}
在我的应用中评论模型也被其他一些模型共享。
例如: - 用户的问题也有评论。 在laravel:Eloquent page
中查找更多详细信息