我正在尝试创建一个“帖子和评论”部分,我设法在一个页面中显示所有帖子,现在我试图在每个帖子下显示评论。在我的模型中,我已经连接了两个表,并且在我的函数中,使用dd();
时,我可以查看帖子和评论,这是我的结果:
我不确定是否在我的视图中正确调用了注释部分,因为出现错误:
此集合实例上不存在属性[activity_post_comments]。 (查看:C:\ xampp \ xampp \ htdocs \ rsapp \ resources \ views \ pages \ timeline.blade.php)
我的功能:
public function timeline()
{
$activityposts = ActivityPost::with('activity_post_comment')
->orderBy('created_at','desc')
->paginate(100);
$posts = Post::orderBy('created_at','desc')->paginate(100);
// dd($activityposts);
return view('pages.timeline')
->with('posts', $posts)
->with('activityposts', $activityposts);
}
查看:
@if(count($activityposts) > 0)
@foreach($activityposts as $activitypost)
<div class="panel panel-default">
<!--
<div class="panel-heading"><a href="#" class="pull-right">View all</a>
<h4>Bootply Editor & Code Library</h4></div>
-->
<div class="panel-body">
<p>
<img src="../storage/user_image/{{ $activitypost->user->user_image }}" width="28px" height="28px">
<b>{{ $activitypost->user->firstname }} {{ $activitypost->user->lastname }}</b>
<span class="pull-right">{{ $activitypost->created_at->format('d-m-Y') }}</span>
</p>
<!--
<div class="clearfix"></div>
<hr>
-->
{{ $activitypost->status_update }}
<hr>
<div class="well">
{{ $activitypost->activity_post_comments->activity_post_comments }};
</div>
<hr>
<form class="form-horizontal" role="form" method="POST" enctype="multipart/form-data" action="{{ action('PagesController@storecomments', $activitypost->id) }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('activity_post_comments') ? ' has-error' : '' }}">
<!-- <label for="activity_post_comments" class="col-md-4 control-label">First Name</label> -->
<div class="col-md-12">
<input id="activity_post_comments" type="text" class="form-control" name="activity_post_comments" required autofocus>
@if ($errors->has('activity_post_comments'))
<span class="help-block">
<strong>{{ $errors->first('activity_post_comments') }}</strong>
</span>
@endif
</div>
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
</div>
</div>
@endforeach
{{$activityposts->links()}}
@else
<p>No new activity from users</p>
@endif
这是我不确定的地方:
{{ $activitypost->activity_post_comment->activity_post_comments }};
答案 0 :(得分:2)
由于activity_post_comment
是一个集合,因此您需要遍历整个集合以获取单个实例。
@foreach ($activitypost->activity_post_comment as $comment)
<p>{{ $comment->activity_post_comments }}</p>
@endforeach
答案 1 :(得分:1)
正如linktoahref所指出的,您不确定那件事是正确的。 $ activitypost和$ activity_post_comment之间的关系是1-n, 或$ activitypost将收集$ activity_post_comment, 因此,在使用collection时,您可以使用for-loop或其他方便的辅助方法。 for循环可能是
@foreach ($activitypost->activity_post_comment as $comment)
<p>{{ $comment->activity_post_comments }}</p>
@endforeach
或者如果您只想要一个activity_post_comments数组
$activitypost->activity_post_comment->pluck('activity_post_comments')