我正在尝试在此菜单中显示与相关类别相关的子类别firsrt类别已显示,但我必须显示相关类别的替代文字?
数据库
控制器
public function index(){
$category=DB::table('category')->where('p_id',0)->get();
return view('front_end/index',compact('category'));
}
html视图
<div class="nav-panel__nav-links nav-links">
<ul class="nav-links__list">
@foreach($category as $firstmenu)
<li class="nav-links__item nav-links__item--has-submenu ">
<a id="cate" class="nav-links__item-link" href="
{{$firstmenu->cate_name}}">
<div class="nav-links__item-body">
{{$firstmenu->cate_name}}
<svg class="nav-links__item-arrow" width="9px" height="6px">
<use xlink:href="public/assets/images/sprite.svg#arrow-rounded-down-9x6"></use>
</svg>
</div>
</a>
<div class="nav-links__submenu nav-links__submenu--type--megamenu nav-links__submenu--
size--nl">
<!-- .megamenu -->
<div class="megamenu ">
<div class="megamenu__body">
<div class="row">
<div class="col-6">
<ul class="megamenu__links megamenu__links--level--0">
<li class="megamenu__item megamenu__item--with-submenu ">
/sub category /
<a href="">T-shirts</a>
<ul class="megamenu__links megamenu__links--level--1">
/sub category /
<li class="megamenu__item"><a href="">short paint</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- .megamenu / end -->
</div>
</li>
@endforeach
</ul>
</div>
答案 0 :(得分:3)
因此,首先,您需要以某种方式获取此子类别。您可以使用雄辩的关系(如果已定义)或简单的连接,如下所示:
数据库查询:
$category = DB::table('category')
->join('subcategory', 'subcategory.category_id', '=','category.id')
->where('p_id',0)
->get();
口才(如果类别具有多个子类别):
类别模型:
public function subcategory()
{
return $this->hasMany(SubCategory::class, 'category_id', 'id');
}
控制器
$category = Category::with('subcategory')->get();
然后仅查看视图中子类别的名称或其他值(重要-如果与您的类别相关的子类别可能不止一个,则必须使用循环遍历所有子类别):
{{$category->subcategory->name}}
或
@foreach($category->subcategory as $sub_cat)
{{$sub_cat->name}}
@endforeach
有关更多信息,请查看Laravel文档: https://laravel.com/docs/6.x/eloquent-relationships
答案 1 :(得分:0)
您已经发布了表格结构
您的关系将像
public function subCategories(){
return $this->hasMany(SELF::class, 'p_id', 'id');
}
public function parentCategories(){
return $this->hasMany(SELF::class, 'p_id', 'id');
}
public scopeParent($query){
return $query->whereNull('p_id');
}
public scopeChild($query){
return $query->whereNotNull('p_id');
}
您应该能够获得类似的类别
$categories = Category::parent()->get();
然后是这样的
foreach($categories->with('subCategories')->get() as $category) {
foreach($category->subCategories as $subCategory) {
}
}