2016-08-11 85 views
2

方案 - 我假設我有數千篇文章,每篇文章有1-1000條評論。 以及我可以簡單地分頁發表10或20與其評論。
這將返回分頁的帖子及其評論。如何分頁在Laravel 5中的評論

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

問題是我想分頁評論,以便每個帖子返回4條評論。那麼如果一篇文章有​​4條評論,我怎麼稱其他評論?

回答

2

我認爲最好的方法是將帖子存儲在一張單獨的桌子上。

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例如使用以下遷移

Schema::create('posts', function(Blueprint $table){ 
    $table->increments('id'); 
    $table->string('title'); 
    $table->timestamps(); 
}); 

現在使用的遷移創建註釋表中創建一個職位表型號,

class Post extends Model 
{ 
    ...  

    public function comments(){ 
     return $this->hasMany('App\Comment'); 
    } 
} 

Comment模型,

class Comment extends Model 
{ 
    protected $fillable = ['post_id', 'c_body', 'name']; 

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


} 

此時,填充兩個數據庫表後:postscomments,您可以然後分別在控制器中對它們進行查詢。 要做到這一點,在控制器的頂部添加兩行: use App\Post; use App\Comment;

現在您所選擇的任何方法在控制,查詢崗位和每個大多數意見如下

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'); 
} 

我的答案很長,儘管我試圖把它縮短。希望它有幫助。