如何计算属于哪个类别的文章?

时间:2016-12-25 16:02:41

标签: laravel laravel-5 laravel-5.2

我有这种关系:

制品

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

CATEGORY有翻译

public function c_translations()
  {
    return $this->hasMany('App\Models\CategoryTranslations', 'category_id');
  }

在文章中我有类别ID,在翻译中我也有category_id。那么我怎么能算出每个类别有多少文章。有什么建议吗?

 $articles = Articles::all();
      foreach($articles as $article ){
      $articles_category = Articles::where('id',$article->id)->withCount('category')->first();

      }

我试过这个但是对于所有类别总是得到0

3 个答案:

答案 0 :(得分:6)

Category模型中定义hasMany关系:

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

然后,您可以使用withCount将其查询为:

$categories = Category::withCount('articles')->get();

将其传递给您的视图,然后您可以访问否。类别的文章:

@foreach ($categories as $category)
  <li>{{ category->title }}</li>
  <li>{{ category->articles_count }}</li>
@endforeach

答案 1 :(得分:0)

使用withCount()方法计算关系。

withCount
  

如果您想要计算关系中的结果数而不实际加载它们,您可以使用{relation}_count方法,该方法会在结果模型上放置{{1}}列。

答案 2 :(得分:0)

我认为你应该使用group by语句。 您选择category_id,COUNT(*)FROM items GROUP BY category_id 这将返回每个category_id

的文章数量