Reputation: 925
I have this relationships:
ARTICLES
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
Upvotes: 2
Views: 2029
Reputation: 17658
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>
@endforeach
Upvotes: 8
Reputation: 2384
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
Upvotes: 0
Reputation: 163768
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.
Upvotes: 0