【问题标题】:Laravel total products count from childs in parent categoryLaravel 总产品数来自父类别中的子项
【发布时间】:2020-12-28 13:25:58
【问题描述】:

我与子类关系很好

在类别模型中

public function products()
    {
      return $this->hasMany(Products::class, 'category', 'id');
    }

   public function sub() {
          return $this->hasMany(SELF::class, 'parent_id')->withCount(['products'])->with('sub');
   }

我想在每个类别和子类别中有产品计数

示例 类别 A 是父级 B 类和 C 类是 A 类的子类 B类有3个产品,C类有2个产品

调用withCount()时如何在A父类中得到product_count 5(B和C类产品总数)?

目前计数为 0,但子类别有产品计数。

非常感谢您的任何想法!

【问题讨论】:

  • 最大嵌套是多少?我的意思是,如果 B 类和 C 类可以有孩子
  • 基本上我会为每个类别获得无限数量的孩子。

标签: php laravel eloquent parent-child categories


【解决方案1】:

获取一个类别的所有产品数量(包括其子类别下的产品)的一种方法是通过两个单独的查询。

假设:

  • 类别 A 的 ID 为 5
  • B 类和 C 类是 A 的子类
//Get the Category record with sub categories
//Select only id column from category
//Select id & parent_id (required as it links the relation) from sub (categories)
$category = Category::with('sub:id,parent_id')
    ->select('id')
    ->findOrFail(5);

//Prepare a collection of just the id's 
$categoryIds = $category->sub->pluck('id')->push($category->id);

//Get the product count
$count = Products::whereIn('category', $categoryIds)->count();

我很感激!它只计算 2 个下一个子项的产品数量,而不是整个嵌套类别。

定义一个从子类别中获取所有 id 的方法

class Category extends Model
{
    public function getSubcategoryIds()
    {
        $ids = $this->sub->pluck('id');
        
        $this->sub->each(function($sub) use(&$ids){            
            if($sub->sub->count()) {            
                $ids->push($sub->getSubcategoryIds());
            }
        });      

        return $ids->flatten();
    }

    //... rest of the class code
}

然后

$category = Category::findOrFail(5);

//Get the subcategory ids deeply nested and add category id to it
$categoryIds = $category->getSubcategoryIds()->push($category->id);


//Get the product count
$count = Products::whereIn('category', $categoryIds)->count();

【讨论】:

  • 我很感激!它只计算 2 个下一个孩子的产品数量,而不是整个嵌套类别。
  • 那么嵌套的深度是多少。例如:B 类有一个子类 D,D 有一个子类 X 等等 - 有多少这样的层次?
  • 在每个父类别中,我有不同数量的嵌套。有没有机会检查嵌套了多少父类别。
  • 不同数量的嵌套是可以的 - 但最多可以有多少嵌套级别?
  • 目前不超过6个子类别
猜你喜欢
  • 2021-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多