php - withCount 与其他属性
问题描述
我有一个allArticlesCount
计算所有文章的功能draft 1
。
$allArticlesCount = Article::where('draft', 1)->count();
我还有一个计算特定类别文章数量的功能,我使用withCount
,但她绝对计算所有文章,我只需要 withdraft 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
反映这一点的属性。
推荐阅读
- named-entity-recognition - IBM Watson NLU 中货币实体到实体提取的低分
- spring - 无法找到 JSP 翻译文件存储在 Google App 引擎中
- hyperledger-fabric - 如何从 Hyperledger Fabric 网络中检索交易以进行审计?
- scala - SBT 错误:“运行时对未定义设置的引用”
- azure-devops - 项目特定的安全设置页面永远不会从浏览器中显示
- html - Angular 6 显示依赖于下拉列表的选定选项
- excel - Excel 模糊查找仅显示 000.01 或 000.00 值
- .net - 赛普拉斯 CY7C68013 在 EPP 模式代码示例
- angular - Angular 6 搜索功能
- multithreading - Postgres 锁在不同的 goroutine 上表现不一致