Home > Software design >  withCount with other attributes
withCount with other attributes

Time:10-07

I have a function allArticlesCount that counts all articles that have draft 1.

$allArticlesCount = Article::where('draft', 1)->count();

I also have a function that counts the number of articles in a specific category, I use withCount , but she counts absolutely all the articles, and I only need with draft 1

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

The question is, how can I make it so that all articles that have draft 1 are counted in the $categories function?

CodePudding user response:

The withCount() function, like the with() function, can use an array as its argument to allow modification of the relationship being counted. In your instance, you'd do the following:

$categories = BlogCategory::withCount(['articles' => function($query){
  $query->where('draft', 1);
}])->get();

This will return your BlogCategory instances, each with a articles_count property indicative of the number of draft articles related to each instance.

Alertnatively, you can define a draftArticles relationship:

public function draftArticles() {
  return $this->hasMany(Article::class)->where('draft', 1);
  // Note: May need to adjust `hasMany()` to reference proper FK column, etc.
}

And perform withCount() on that instead:

$categories = BlogCategory::withCount('draftArticles')->get();

Each BlogCategory instance would have a draft_articles_count property reflecting that.

  • Related