我有两个Model(类别,品牌)与laravel中的一对多关系(hasMany)相关,就像category hasMany brands
。现在,我想在一个选择标签中显示品牌数据,在另一个选择标签中显示类别模型数据。
$category=Category::with('brands')->get();
return view('product.add')->with('category',$category);
<div class="form-group">
<select name="category_id" class="input">
<option value="">Select Main Category</option>
@foreach($category as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
@endforeach
</select>
</div>
<div class="form-group">
<select name="brand_id" class="input">
@foreach($brands->brands as $brand)
<option value="{{$brand->id}}">{{$brand->name}}</option>
@endforeach
</select>
</div>
它不起作用
答案 0 :(得分:2)
您可以执行以下简单操作:
<div class="form-group">
<select name="category_id" class="input">
<option value="">Select Main Category</option>
@foreach($category as $cat)
<option value="{{$cat>id}}">{{$cat->name}}</option>
@endforeach
</select>
</div>
<div class="form-group">
<select name="brand_id" class="input">
@foreach($category as $cat)
@foreach($cat->brands as $brand)
<option value="{{$brand->id}}" category="{{$cat->id}}">{{$brand->name}}</option>
@endforeach
@endforeach
</select>
</div>
,您只需要使用javascript(jquery)
显示所选选项的品牌 $('[name="category_id"]').on('change',function() {
if($(this).val() != '') {
$('[name="brand_id"] option').hide();
$('[name="brand_id"] option[category="'+$(this).val()+'"]').show();
} else {
$('[name="brand_id"] option').show();
}
});