我有一个简单的查询,用主要类别和子类别填充菜单。这项工作完美无缺
// in controller
$cat=Categories::all();
View::share('categories_menu',$cat);
// in view
@foreach($categories_menu as $category_menu)
@if($category_menu->has('subcategories'))
<ul class="nav nav-stacked cat-nav">
<li>
<a href="#">{{ $category_menu['category_name'] }} </a>
@if($category_menu->subcategories->count())
<ul>
@foreach($category_menu->subcategories as $subcategory)
<li class=""><a href="#">{{$subcategory->sub_cat_name}}</a></li>
@endforeach
</ul>
@endif
</li>
@else
<li><a href="#"><i class="fa fa-link"></i> <span>{{ $category_menu->category_name }}</span></a></li>
@endif
</ul>
@endforeach
这样输出就像
Main Category
-Sub Cat
-Sub Cat
Second main category
-Sub in second main category
...
问题是它还加载了空的子类别。我不想显示它们,我尝试通过加入所有三个表来更改查询 - category
,sub_categories
,products
这是到目前为止的查询
$cat = Categories::select('*', DB::raw('category.category_id AS category_id'))
->leftJoin('products', function($join) {
$join->on('products.category_id', '=', 'category.category_id');
})
->leftJoin('sub_category', function($secondjoin){
$secondjoin->on('sub_category.category_id', '=', 'category.category_id');
})
->whereNotNull('products.sub_cat_id')
->get();
它应该只显示两个主要类别,每个类别有一个子类别。在图像上,您可以看到我的产品表
Category 1
-sub1
Category 2
-sub3
如果需要更多来源或我能提供的东西。
使用模型更新:
分类模型
class Categories extends Eloquent {
protected $table = 'category';
protected $primaryKey = 'category_id';
public $timestamps = false;
public function products()
{
return $this->hasMany('Product', 'category_id');
}
public function subcategories()
{
return $this->hasMany('SubCategories', 'category_id');
}
}
子类别模型
class SubCategories extends Eloquent {
protected $table = 'sub_category';
protected $primaryKey = 'sub_cat_id';
public $timestamps = false;
public function category()
{
return $this->belongsTo('Category', 'category_id');
}
public function products()
{
return $this->hasMany('Product', 'sub_cat_id');
}
}
产品型号
class Product extends Eloquent {
protected $table = 'products';
protected $primaryKey = 'product_id';
public function categories()
{
return $this->hasMany('Categories', 'category_id');
}
public $timestamps = false;
}
答案 0 :(得分:1)
@foreach($categories_menu as $category_menu)
@if($category_menu->has('subcategories'))
<ul class="nav nav-stacked cat-nav">
<li>
<a href="#">{{ $category_menu['category_name'] }} </a>
@if($category_menu->subcategories->count())
<ul>
@foreach($category_menu->subcategories as $subcategory)
@if($subcategory->products->count())
<li class=""><a href="#">{{$subcategory->sub_cat_name}}</a></li>
@endif
@endforeach
</ul>
@endif
</li>
@else
<li><a href="#"><i class="fa fa-link"></i> <span>{{ $category_menu->category_name }}</span></a></li>
@endif
</ul>
@endforeach
我添加了子系统的条件,只有当他们的产品数量大于0时才会显示。