laravel - 子模型的负载计数关系
问题描述
我建立了模型并试图检索与特定模型相关的模型的数量,但是我使用它的方式的问题让我返回了所有关系的数量。
以下是我的案例的描述,我有这些模型:
Category
模型
public function subcategories()
{
return $this->belongsToMany('App\SubCategory');
}
/**
* Get the documents for the category
*/
public function documents()
{
return $this->hasMany('App\Document');
}
SubCategory
模型
public function categories()
{
return $this->belongsToMany('App\Category');
}
/**
* Get the documents for the subcategory
*/
public function documents()
{
return $this->hasMany('App\Document');
}
我想加载 和 之间的关系计数Subcategory
,Document
仅用于 selected Category
,我尝试了以下方法,但它加载了 和 之间的所有SubCategory
计数Document
:
Category::find($selectedCategory)->subcategories()->withCount('documents')->get()->sortBy('name');
解决方案
推荐阅读
- r - 复制矩阵的列而不更改行
- android - 所有 com.android.support 库必须使用相同版本的 appcompat-v7:28.0.0
- reactjs - React-Day-Picker 弹出位置
- gams-math - GAMS - 单位阶跃函数
- angular - Angular 6 + Laravel 5.6:httpClient.post 的 CORS 问题
- python - 根据烧瓶 SQLAlchemy 中的 func.sum() 值将结果传递给模板
- json - 在 powershell 的 TFS 版本定义中使用 Newtonsoft.Json
- amazon-s3 - 零星的 Lambda 超时
- python-3.x - 如何在散景 HoverTool 工具提示中使用变量名?
- sockets - 使用 C 的 TCP 套接字(服务器)