我在页面上有父类和子类。我想要做的是当没有产品,并且在某些父类别中没有分配子类别而不在页面上显示。
所以我在分类模型中有这个
public function item()
{
return $this->hasMany('Item','category_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id');
}
public function getCategories()
{
$categoires = Category::where('parent_id',0)->get();
$categoires = $this->addRelation($categoires);
return $categoires;
}
public function selectChild( $id )
{
$categoires = Category::where('parent_id',$id)->where('published', 1)->get();
$categoires = $this->addRelation($categoires);
return $categoires;
}
这在控制器中
public function index()
{
$Category = new Category;
$allCategories = $Category->getCategories();
return view('frontend.home', compact('allCategories', 'unviewedMessagesCount'));
}
这在刀片视图上
@foreach($allCategories as $category)
{!!$category->title!!} ({!! $category->itemCount!!})
<p class="card-text">
@foreach($category->subCategory as $subcategory)
{!!$subcategory->title!!} {!! $subcategory->itemCount !!}
@endforeach
</p>
<a href="{!!route('list',array($category->id))!!}" class="btn btn-primary">View Category</a>
@endforeach
这是类别表中的记录样本有列
id | title | parent
1 Main cat 0
2 Sub-Cat 1
3 Sub-Cat 2 1
4 Main cat 2 0
因此每个父项为0,每个子项(子类别)都具有父ID
item
表还引用了category
表 - &gt;专栏category_id
如果没有任何项目和没有孩子在页面上显示,我无法弄清楚如何制定条件。
答案 0 :(得分:1)
在控制器
中$allCategories = Category::where('parent_id', 0)->has('children.item')
->with(['children'=> function($query){
$query->withCount('item');
}])
->get()
->each(function($parentCategory){
// if you wants calculate sum child category item count and assign to parent category item_count.
$parentCategory->item_count = $parentCategory->children->sum(function ($child) { return isset($child->item_count)?$child->item_count:0;});
});
return view('frontend.home', compact('allCategories'));
在此查询中,只会执行一个查询,它会返回您的所有需求。
在Blade View文件中
@foreach($allCategories as $category)
{!!$category->title!!} ({!! $category->item_count!!})
<p class="card-text">
@foreach($category->children as $subcategory)
{!!$subcategory->title!!} {!! $subcategory->item_count !!}
@endforeach
</p>
<a href="{!!route('list',array($category->id))!!}" class="btn btn-primary">View Category</a>
@endforeach