问题描述
id:1 || name:category_1 || parent_id:NULL
id:2 || name:subcategory_1.1 || parent_id:1
id:3 || name:subcategory_1.2 || parent_id:1
id:4 || name:category_2 || parent_id:NULL
id:5 || name:subcategory_2.1 || parent_id:4
id:6 || name:subcategory_2.2 || parent_id:4
id:7 || name:category_3 || parent_id:NULL
大家好,我已经建立了这种类型的数据库来管理类别和子类别。 我想设置一个循环,允许我只显示 category_3 但我不知道该怎么做。 实际上,我想排除所有有孩子的父母。
仅查看我使用的父母:
@foreach($categories as $parent)
<option value="{{ $parent->id }}">{{$parent->name}}</option>
@endforeach
查看父母和孩子:
@foreach($categories as $parent)
<option value="{{ $parent->id }}">{{$parent->name}}</option>
@if($parent->children)
@foreach($parent->children as $children
<option value="{{ $children->id }}">{{$children->name}}</option>
@endforeach
@endif
@endforeach
类别控制器
public function create()
{
$categories = Category::with('children')->whereNull('parent_id')->where('status','=',1)->get();
return view('backend.category.create')->with([
'categories' => $categories
]);
}
类别(模型)
public function children()
{
return $this->hasMany('App\Models\Category','parent_id');
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)