Laravel 5 如何在Laravel 5中对帖子中的评论进行分页

Laravel 5 如何在Laravel 5中对帖子中的评论进行分页,laravel-5,pagination,Laravel 5,Pagination,情景- 我假设我有数千篇文章,每篇文章都有1-1000条评论。 好吧,我可以简单地用10或20页的篇幅给这篇文章加上评论。 这将返回带有注释的分页帖子 $Posts = \App\Post::where('published',true)->with('comments')->paginate(10); 问题是我想对评论进行分页,这样每个帖子都会返回4条评论。那么,如果一篇文章有超过4条评论,我该如何调用其他评论呢?我认为最好的方法是将文章存储在一个单独的表中。例如,使用以下迁移创

情景- 我假设我有数千篇文章,每篇文章都有1-1000条评论。 好吧,我可以简单地用10或20页的篇幅给这篇文章加上评论。
这将返回带有注释的分页帖子

$Posts = \App\Post::where('published',true)->with('comments')->paginate(10);

问题是我想对评论进行分页,这样每个帖子都会返回4条评论。那么,如果一篇文章有超过4条评论,我该如何调用其他评论呢?

我认为最好的方法是将文章存储在一个单独的表中。例如,使用以下迁移创建一个post表

Schema::create('posts', function(Blueprint $table){
    $table->increments('id');
    $table->string('title');
    $table->timestamps();
});
现在使用迁移创建注释表:

   Schema::create('comments', function(Blueprint $table){
        $table->increments('id');
        $table->integer('post_id')->unsigned();           
        $table->string('name');
        $table->text('comment_body');
        $table->timestamps();

        $table->foreign('poem_id')->references('id')->on('posts'); 
    });
在这两个表之间创建一对多关系,如下所示:

对于
Post
型号

class Post extends Model
{
    ...     

    public function comments(){
        return $this->hasMany('App\Comment');
    }
}
class Comment extends Model
{
    protected $fillable =  ['post_id', 'c_body', 'name'];

    public function posts(){
        return $this->belongsTo('App\Poem', 'post_id');
    }   


}
对于
注释
模型

class Post extends Model
{
    ...     

    public function comments(){
        return $this->hasMany('App\Comment');
    }
}
class Comment extends Model
{
    protected $fillable =  ['post_id', 'c_body', 'name'];

    public function posts(){
        return $this->belongsTo('App\Poem', 'post_id');
    }   


}
此时,在填充两个数据库表:
posts
comments
之后,您可以在控制器中分别查询它们。 为此,请在控制器顶部添加两行:
使用App\Post
使用App\Comment

现在,在该控制器中选择的任何方法中,查询每个most的帖子和评论,如下所示

public function index(){
    $posts = Post::where('published',true);
    $comments = Post::where('published',true)->comments;
   // pass this data to your view
   return view('anyview', compact('posts', 'comments');
}
我的答案很长,尽管我尽量简短。希望有帮助