2017-01-25 40 views
1

我要在Laravel創建博客。現在我在博客中發佈表單分類,並且我只能根據帖子顯示分頁,但是我想僅針對與分類標識具有關聯性的帖子顯示分頁。根據laravel關係表中的數據顯示paginate

我的代碼中存在一些問題,請幫助我解決我的問題。

在控制器源代碼:

//this code show posts according to category id 
$postCatId = $request->postCatId; 
$postList =PostCat::with("posts")->where('id',$postCatId)->get(); 

//this code show paginate according to posts has relation with category 
$paginate=PostCat::with("posts")->where('id',$postCatId)->paginate(2); 

這則返回$postList$paginate在視圖以查看

//show posts has relation with category id 
@foreach($PostList as $post) 
    @foreach($post->posts as $post_item) 
    {{$post_item->id}} 
    @endforeach 
@endforeach 


//show paginate according to posts has relation with category id 
{{$paginate->links()}} 

但我不能表現出與職位PAGINATE有關係,與分類號

+0

你想分頁有哪些類別的所有職位?因爲現在你正在對類別進行分頁,而不是帖子。 –

+0

這個代碼只是分類的分類,但我想顯示分頁根據職位有關係與類別 – alireza

回答

0

I F你想分頁有一個類別的職位,使用此查詢,而不是兩個電流的:

$posts = Post::with('category') 
      ->has('category') 
      ->where('id', $postCatId) 
      ->paginate(2); 

請確保您有在Post模型category()關係:

public function category() 
{ 
    return $this->belongsTo('App\PostCat'); 
} 

在視圖中遍歷$posts和渲染鏈接:

@foreach($posts as $post) 
    <div>Post ID is {{ $post->id }} and category ID is {{ $post->category->id }}</div> 
@endforeach 

{{ $paginate->render() }} 
+0

不,我認爲它的錯誤,因爲這個代碼: $ posts = Post :: with('category') - > has('category') - > where('id',$ postCatId) - > paginate(2); 只顯示類別頁面 – alireza

+0

不,此代碼提取所有具有類別的帖子,並忽略沒有類別的帖子。然後它是分頁結果(分頁文章)。 –

0

許多在Laravel 5一對多的關係更簡單的方式和這個分頁:

分類型號:

public function articles() 
{ 
    return $this->belongsToMany('App\Article'); 
} 

文章型號:

public function categories() 
{ 
    return $this->belongsToMany('App\Category'); 
} 

當你想從與分頁類別下載的所有帖子/文章:

$category = Category::where('slug', $slug)->firstOrFail(); 
$category_articles = $category->articles()->orderBy('created_at', 'desc')->paginate(10);