根据多对多关系确定选择的选项

Determine selected options based on many-to-many relationship

我有三个 table:产品、类别和 category_product。

在我的编辑表单页面中,我在 select 框中显示类别和子类别值。 所选类别选项保存在数据透视表 table category_product 中。这个 table 有 product_id 和 category_id.

这是我的代码。

产品型号

public function category() {
  return $this->belongsToMany('App\Models\Category');
}

类别模型:

public function products()
{
    return $this->belongsToMany(Product::class);
}

编辑产品页面视图:

<select name="category_id[]" class="form-control" multiple size = 10>
   @foreach ($parentCategories as $parentCategory)
       <option value="{{ $parentCategory->id }}">{{ $parentCategory->name }}</option>
       @if(count($parentCategory->subcategory))
         @include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
       @endif
   @endforeach
</select>

subcats-select 视图

@foreach($subcategories as $subcategory)
  <option value="{{ $subcategory->id }}">---{{ $subcategory->name }}</option>
    @if(count($subcategory->subcategory))
      @include('includes.subcats-select',['subcategories' => $subcategory->subcategory])
    @endif
  </div>
@endforeach

如何将“selected”属性添加到所选类别选项中,以便在编辑页面时正确应用更改?

您可以通过以下方式获得pivot table columns

产品型号

public function category() {
  return $this->belongsToMany('App\Models\Category')->withPivot('selected');
}

编辑产品页面视图:

<select name="category_id[]" class="form-control" multiple size = 10>
   @foreach ($parentCategories as $parentCategory)
       <option value="{{ $parentCategory->id }}" selected="{{ $parentCategory->pivot->selected }}">
           {{ $parentCategory->name }}
       </option>
       @if(count($parentCategory->subcategory))
         @include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
       @endif
   @endforeach
</select>

编辑:虽然以上答案可能对其他人有帮助,但它没有回答问题。所以这是我在聊天中澄清后的第二次尝试。

<select name="category_id[]" class="form-control" multiple size = 10>
   @foreach ($parentCategories as $parentCategory)
       <option value="{{ $parentCategory->id }}"{{ $product->category->contains($parentCategory->id) ? 'selected' : '' }}>
           {{ $parentCategory->name }}
       </option>
       @if(count($parentCategory->subcategory))
         @include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
       @endif
   @endforeach
</select>