计算具有特定类别和标签laravel的帖子

时间:2017-02-11 15:16:17

标签: php mysql laravel laravel-5.3 blade

我有3个模型Post, Tag and CategoryPost modelTag model与数据透视表存在多对多的关系,Post modelCategory model属于一对多关系。

例如,假设我有以下标签和类别:

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个数组,但计算了数据库中的所有帖子。我在这里缺少什么难题或者这是不可能的?

1 个答案:

答案 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.如果我找到你的话。