分页图层关系



我有两个表,我们用Post和Comment模型来命名posts和comments。

Post.php
public function comments(){
return $this->hasMany(Comment::class);
}
Comment.php
public function post(){
return $this->belongsTo(Post::class);
}

现在我想加载带有评论的Post,在Post和comments上都有分页。

我已经尽力了,

Post::with('comments')->pagenate();

上面的代码只对Post Model进行分页。所以我尝试了下面的代码,但没有运气。

In Post.php
public function comments(){
return $this->belongsTo(Comment::class)->paginate(5);
}
Post::with('comments')->pagenate();

在控制器中,您必须将Post变量和每个Post的Comments变量与它分页,然后返回变量


$posts = Post::orderBy('id', 'desc')->paginate(10);
foreach ($posts as $post)
$comments = $post->comments()->paginate(2);
return view('post.index', ['posts' => $posts, 'comments' => $comments]);

现在,在刀片视图中,您只需要将@foreach的comments变量放在帖子中,并为您添加链接到页面。


@foreach( $comments as $comment )
<p> {{ $comment->desc }}</p>
@endforeach
{{ $comments->links() }}

最新更新