如何在 <select> 标签中的 laravel blade 中声明子类别及其 init 子类别

how to declare subcategory and its inifit subcategory in laravel blade in the <select> tag

我可以获得我的类别及其无限子类别 但我不知道如何在这种状态下的选择选项标签中显示它们: (我只想在 blade 中显示属于其 parent 的子类别(及其无限子类别)

类别

cloth
 -Men
  --Tshirt

 -Women 
  --Tshirt

这是我的类别模型方法代码

public function subcategories()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

这是我的 迁移

$table->id();
            $table->string('title');
            $table->string('slug');

            $table->foreignId('parent_id')
                  ->nullable()
                  ->constrained('categories')
                  ->cascadeOnDelete()
                  ->cascadeOnUpdate();

这是我的index.blade.php视图

<select
class="form-select @error('parent') is-ivalid @enderror"
required="">
<option selected="" value="0">None</option>
@foreach($categories as $category)
    @if($category->{'parent_id'} === null)
        <option
            value="{{$category->{'id'} }}">
            {{$category->{'title'} }}
        </option>
            @if(count($category->subcategories ))
                @include('admin.layouts.partials.subcategory' , ['sub'=>$category->subcategories])
            @endif

    @endif
@endforeach
</select>

这是我的 partials 子类别 blade

@foreach($sub as $child)
    <option value="{{$child->{'id'} }}">
        {{$child->{'title'} }}
    </option>

    @if(count($child->subcategories))
        @include('admin.layouts.partials.subcategory' , ['sub'=>$child->subcategories])
    @endif
@endforeach

假设你的关系是正确的。尝试将 blade 部分更改为:

@foreach ($categories as $category)
    <optgroup label={{ $category->title }}>
        @if(isset($category->subcategories))
            @foreach ($category->subcategories as $subcategories)
                <option value={{ $subcategory->id }}>
                    {{ $subcategory->title }}
                </option>
            @endforeach
        @else
            <option value="undefined">No available subcategories</option>
        @endif
    </optgroup>
@endforeach

有了这个,您可以将所有类别打印为一个选项组 (optgroup),对于您打印的每个类别,您都可以将其子类别打印为该 optgroup 标签中的选项。如果类别没有子类别,它将显示 No available subcategories