【发布时间】:2021-08-13 14:02:04
【问题描述】:
我有三个表:products、categories 和 category_product。
在我的编辑表单页面中,我在选择框中显示类别和子类别值。 选择的类别选项保存在数据透视表 category_product 中。这个表有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-选择视图
@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”属性添加到所选类别选项中,以便在编辑页面时正确应用更改?
【问题讨论】:
标签: php laravel eloquent laravel-8 eloquent-relationship