2017-02-11 73 views
0

我有3個模型Post, Tag and CategoryPost modelTag model與數據透視表存在多對多關係,Post modelCategory model處於一對多關係。用特定的類別和標籤計算帖子laravel

例如假設我有以下標籤和分類:

tag name = php,

category name = tutorial, project, testing

no. of post having above attribute = 3 [ all post have different category, same tag]

我想算職位並使上述的分類和標籤顯示類別名稱php在視圖中名爲archive-php

這是我迄今所做的:在控制器

我的方法

public function countTag() 
{ 
    $posts = Post::whereHas('tag', function($r) { 
      $r->where('name','=', "php"); 
     })->get(); 
    return view('archive-php') 
      ->withPosts($posts) 
} 

我的視圖代碼:

@foreach ($posts as $post) 
    <li><a href="#">{{ucfirst($post->category->name)}}</a> 
     {{$post->count()}} 
    </li> 
@endforeach 

上面的代碼成功地展示了關聯類別名稱( 3類別名稱)dd($posts);轉儲3個數組,但統計數據庫中的所有文章。我在這裏錯過了什麼樣的謎題或者這是不可能的?

+0

你想要計算[tag] [php]的[category]類型的[posts]數目? –

+0

是的,那就是我想要做的。 –

回答

1

要實現這一目標,您應該獲得所有類別。然後獲取/計算已php標籤

1的職位 - 方法

$categories = Category::all(); 

foreach($categories as $category) { 
    $category->phpPosts = Post::where('category_id', '=', $category->id)->whereHas('tag', function($r) { 
      $r->where('name','=', "php"); 
     })->get(); 
} 

然後使用它是這樣的:

@foreach ($categories as $category) 
    <li><a href="#">{{ucfirst($category->name)}}</a> 
     {{ $category->phpPosts->count() }} 
    </li> 
@endforeach 

它可以通過簡單的方式問題採取行動,如:

2 - 方法

$categories = App\Category::with(['posts' => function ($query) { 
    $query->whereHas('tag', function($r) { 
      $r->where('name','=', "php"); 
     }); 
}])->get(); 

但我不確定它是否正確。試試方法1.如果我正確地得到了你。

+0

感謝方法1爲我工作。 –

相關問題