请原谅我的糟糕的语言:)我有一个表格,上面有这样的多级分类:
category_id ------ category_name--------parent_id
1------------------sample 1 ------------ NULL
2------------------sample 2 ------------ 1
3------------------sample 3 ------------ NULL还有..。
现在,我需要在select选项菜单中包含此数据
这是我的表格:
<div class="form-group">
<label class="col-sm-2 control-label">مادر</label>
<div class="text-right col-sm-10">
<select name="parent_id" class="select2 form-control" id="parent_id">
<option value="">انتخاب دسته مادر</option>
@foreach ($categories as $cat)
<option value="{{ $cat -> category_id }}"
{{ isset($productItem) && $productItem->category_id == $cat->category_id ? 'selected':'' }}
>{{ $cat -> category_name }}</option>
@endforeach
</select>
</div>
</div>发布于 2018-09-27 07:21:12
您应该使用<optgroup>来创建一些“嵌套”选项。检查this example。
你的代码应该是:
<select name="parent_id" class="select2 form-control" id="parent_id">
<option value="">انتخاب دسته مادر</option> <!-- default -->
@foreach ($categories->where('parent_id', null) as $cat) <!-- first level only: no parent -->
<!-- if parent must also be selectable, you can add an option for it before its optgroup -->
<option value="{{ $cat->category_id }}">
{{ $cat->category_name }}
</option>
@if($cat->children->count()) <!-- if has children -->
<optgroup label="{{$cat->category_name}}"> <!-- display parent optgroup and within child categories option -->
@foreach($cat->children as $child)
<option value="{{ $child -> category_id }}">
{{ $child -> category_name }}
</option>
@endforeach
</optgroup>
@endif
@endforeach
</select>这应该会创建:
放在optgroup之前的每个父categories
<option>的<optgroup>每个子类别的父categories<option> 发布于 2018-09-27 01:19:44
but in level 3 I have the problem
我改变了我的代码:
<select name="parent_id" class="select2 form-control" id="parent_id">
<option value="">انتخاب دسته مادر</option>
@foreach ($categories as $cat)
@if($cat -> parent_id == NULL)
<option value="{{ $cat -> category_id }}">
{{ $cat -> category_name }}
</option>
@endif
@if ($cat->children->count() > 0)
@foreach($cat->children as $child)
<option value="{{ $child -> category_id }}">
{{ $child -> category_name }}
</option>
@endforeach
@endif
@endforeach
</select>发布于 2020-06-09 20:59:41
在希望找到一个很好地使用Laravel的答案后,我最终放弃了,只是编写代码来做我想做的事情,结果它比我预期的要小。
public function get_categories()
{
$categories = Category::where('parent',null)->get();
while(count($categories) > 0){
$nextCategories = [];
echo "<option value='.$categories->.'>'.$categories->name .'</option";
foreach ($categories as $category) {
$childCategories = Category::where('parent',$category->id)->get();
echo "<option value='.$categories->.'>'.$childCategories->name .'</option";
}
}}
https://stackoverflow.com/questions/52521718
复制相似问题