首页 > 解决方案 > 子模型的负载计数关系

问题描述

我建立了模型并试图检索与特定模型相关的模型的数量,但是我使用它的方式的问题让我返回了所有关系的数量。

以下是我的案例的描述,我有这些模型:

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');
}

我想加载 和 之间的关系计数SubcategoryDocument仅用于 selected Category,我尝试了以下方法,但它加载了 和 之间的所有SubCategory计数Document

Category::find($selectedCategory)->subcategories()->withCount('documents')->get()->sortBy('name');

标签: laraveleloquent

解决方案


推荐阅读