Question: How to count how many articles belongs which category?


How to count how many articles belongs which category?

Answers 3
Added at 2016-12-25 17:12

I have this relationships:


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

CATEGORY have translations

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

In articles i have category id, also in translations i have category_id. So how can i count how many articles have each category. Any suggestion?

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


I tried this but always get 0 for all of categories

nr: #1 dodano: 2016-12-25 17:12

Use withCount() method to count relation.

Model::where('id', $id)->withCount('relation')->first();

If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models.

nr: #2 dodano: 2016-12-25 17:12

I think you should use a group by statement. You select category_id,COUNT(*) FROM articles GROUP BY category_id This will return the number of articles for each category_id

nr: #3 dodano: 2016-12-25 17:12

Define a hasMany relation in your Category model as:

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

Then you can use withCount to query it as:

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

Pass it to your view and then you can access the no. of articles of category as:

@foreach ($categories as $category)
  <li>{{ category->title }}</li>
  <li>{{ category->articles_count }}</li>
Source Show
◀ Wstecz