我试图显示父项和子类别上的项目数。到目前为止,计数仅在子类别中可见,但仅在分配给父目录的项目显示0
。我在Category
模型父类别上未显示项目数
public function addRelation($categoires)
{
$categoires->map(function($item, $key)
{
$sub = $this->selectChild($item->id);
$item->itemCount = $this->getItemCount($item->id , $item->parent_id);
return $item = array_add($item, 'subCategory', $sub);
});
return $categoires;
}
public function getItemCount($category_id, $parent_id)
{
if($parent_id == 0)
{ // for root-caregory
$ids = Category::select('id')->where('parent_id', $category_id)->get();
$array = array();
foreach ($ids as $id)
{
$array[] = $id->id;
}
return Item::whereIn('category_id', $array)->count();
}
else
{
return Item::where('category_id', $category_id)->count();
}
}
在我的刀片添加了这个在控制器
$Category = new Category;
$allCategories = $Category->getCategories();
return view('home', compact('allCategories'));
而且
@foreach($allCategories as $category)
<div class="card-body">
<h4 class="card-title">{!!$category->title!!} <span class="badge badge-primary badge-pill">({!! $category->itemCount !!})</span></h4>
</div>
@endforeach
itemCount
是(0)时,产品在Parent
类别。
有是你的逻辑问题!没有任何情况下其他区块将被执行,总是只会执行第一个区块! – Maraboc
还有一件事,你可以将集合'$ ids'转换为像这样的'$ ids-> toArray()'这样的数组,它可以循环使用它的项目;并且你是否知道你应该做什么? – Maraboc
@Maraboc,否则执行块。在foreach里面,我有另一个涉及子类别的foreach。正如我所说的那样,它正在按照我所说的那样工作,这就是为什么我将它从问题中删除的原因。不,我没有计算出如何显示主要类别中的项目数量。 – Peter