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

uzh*_*has 2 laravel laravel-5 laravel-5.2

我有这种关系:

文章

 public function category()
    {
      return $this->belongsTo('App\Models\Categories');
    }
Run Code Online (Sandbox Code Playgroud)

CATEGORY有翻译

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

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

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

      }
Run Code Online (Sandbox Code Playgroud)

我试过这个,但总是得到所有类别的0

Ami*_*pta 7

hasManyCategory模型中定义关系:

public function articles()
{
    return $this->hasMany('App\Models\Article');
}
Run Code Online (Sandbox Code Playgroud)

然后你可以用withCount它来查询:

$categories = Category::withCount('articles')->get();
Run Code Online (Sandbox Code Playgroud)

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

@foreach ($categories as $category)
  <li>{{ category->title }}</li>
  <li>{{ category->articles_count }}</li>
@endforeach
Run Code Online (Sandbox Code Playgroud)