首页 > 解决方案 > withCount 与其他属性

问题描述

我有一个allArticlesCount计算所有文章的功能draft 1

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

我还有一个计算特定类别文章数量的功能,我使用withCount,但她绝对计算所有文章,我只需要 withdraft 1

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

问题是,我怎样才能使所有文章draft 1都计入$categories函数中?

标签: phplaravel

解决方案


withCount()函数一样,该with()函数可以使用数组作为其参数,以允许修改被计算的关系。在您的实例中,您将执行以下操作:

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

这将返回您的BlogCategory实例,每个实例都有一个articles_count属性,指示draft与每个实例相关的文章数量。

或者,您可以定义一个draftArticles关系:

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

withCount()改为执行:

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

每个BlogCategory实例都有一个draft_articles_count反映这一点的属性。


推荐阅读