如果选项 ID 位于边栏选项卡视图的数组列表中,则 Laravel 将选项设置为选中



>我在控制器中进行了查询并将其发送到我的刀片:

public function editContractorAssociation(DeveloperContractorAssociation $developer_contractor_association, Request $request)
{
$id = $request->id;
$developer_contractor_association = DeveloperContractorAssociation::whereHas('defect_types', function ($query) use($id) {
$query->where('developer_contractor_associations.id', $id);
})->orwhereHas('contractor', function ($query) use($id) {
$query->where('developer_contractor_associations.id', $id);
})->first();
return view('dev-admin.contractors.associations.edit', ['developer_contractor_association' => $developer_contractor_association]);
}

当我在刀片中呼叫{{ $developer_contractor_association->defect_types }}时,我得到这个:

[
{
"id":2,
"title":"Wiring",
"details":"Fix wiring",
"created_by":"22",
"created_at":"2019-09-04 11:39:48",
"updated_at":"2019-09-04 11:39:48",
"deleted_at":null,
"is_custom":1,
"developer_id":1,
"pivot":{"dca_id":87,"defect_type_id":2}},
{"id":3,"title":"Plumbing",
"details": "Fix Pipe",
"created_by":"22",
"created_at":"2019-09-04 11:40:07",
"updated_at":"2019-09-04 11:40:07",
"deleted_at":null,
"is_custom":1,
"developer_id":1,
"pivot":{"dca_id":87,"defect_type_id":3}
}
]

现在我有一个选择字段,列出了所有存在的缺陷类型:

<select class="selectpicker {{ $errors->has('defect-type-id') ? 'is-invalid' : '' }}" name="defect-type-id[]" id="defect-type-id" multiple data-style="selectpicker-style" data-width="100%" title="Defect Types">
@foreach(AppDefectType::select('id','title')->get() as $defect_type)
<option value="{{$defect_type->id}}">{{$defect_type->title}}</option>
@endforeach
</select>

填充选择字段的选项时,如何检查id是否在defect_type_idJSON 中并将选项设置为选中。像这样:

<select class="selectpicker {{ $errors->has('defect-type-id') ? 'is-invalid' : '' }}" name="defect-type-id[]" id="defect-type-id" multiple data-style="selectpicker-style" data-width="100%" title="Defect Types">
@foreach(AppDefectType::select('id','title')->get() as $defect_type)
{{if $defect_type->id in $defect_type_list}}
<option value="{{$defect_type->id}}">{{$defect_type->title}} selected</option>
{{else}}
<option value="{{$defect_type->id}}">{{$defect_type->title}}</option>
@endforeach
</select>

假设您的defect_types关系返回 Laravel 集合,您可以使用几个集合方法:

@foreach(AppDefectType::select('id','title')->get() as $defect_type)    
<option value="{{$defect_type->id}}"
@if($developer_contractor_association->defect_types->pluck('id')->contains($defect_type->id))
selected
@endif
>
{{$defect_type->title}}
</option>
@endforeach

pluck('id')返回一个defect_typeid集合,然后您可以使用contains($defect_type->id)检查所有defect_type的当前小版本是否在该集合中。

您可以使用containsstrict()而不是contains(),因为这可以进行严格的比较。

相关内容

  • 没有找到相关文章

最新更新