gpt4 book ai didi

php - withCount 与其他属性

转载 作者:行者123 更新时间:2023-12-02 16:05:42 25 4
gpt4 key购买 nike

我有一个函数 allArticlesCount,它计算所有有 draft 1 的文章。

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

我还有一个统计特定类别文章数量的函数,我用的是withCount,但是她统计的绝对是所有文章,我只需要with draft 1

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

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

最佳答案

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反射(reflect)这一点的属性(property)。

关于php - withCount 与其他属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69469943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com