我有3個模型Post, Tag and Category
。 Post model
和Tag model
與數據透視表存在多對多關係,Post model
和Category 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個數組,但統計數據庫中的所有文章。我在這裏錯過了什麼樣的謎題或者這是不可能的?
你想要計算[tag] [php]的[category]類型的[posts]數目? –
是的,那就是我想要做的。 –