我试图在父类和子类上显示项目数。到目前为止,计数仅在子类别上可见,但当项目仅分配给父目录时显示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
类别时, Parent
为(0)。
答案 0 :(得分:0)
经过讨论,我们有一个simlpe查询你想要这样做:
public function getItemCount( $category_id)
{
return Item::where('category_id', $category_id)->count();
}
或者,如果你有关系,你可以这样做:
public function addRelation( $categoires )
{
$categoires->map(function( $item, $key)
{
$sub = $this->selectChild($item->id);
$item->itemCount = $item->items()->count();
return $item = array_add($item, 'subCategory', $sub);
});
return $categoires;
}