将另一个表中的选择保存在CRUD应用程序中

时间:2019-11-27 14:53:28

标签: laravel crud

所以我有一个Categories表和一个Gender表。在类别表单中,您可以选择自己的性别,该性别来自Gender表。

问题在于,当您要编辑内容时,您选择的选项不显示。完成类别后。但是,它确实在数据库的类别cte_gender_id中显示为整数。 (1、2或3)

这是我的CategoryController:

$category = Category::find($id);
$array_category_gender_id = array();
$gender_id = $category->cte_gender_id;

$genders = Geslacht::where("gen_id", $gender_id)->get();

foreach($genders as $gender){
$array_category_gender_id[] = $gender->gen_name;
}

和html:

<label>Gender</label>
<select name="gender_id" class="form-control" id="gender_id">
    <option disabled selected value>Select a gender...</option>
    @foreach($genders as $gender)
        <option value="{{ $gender->gen_id }}" {{ ($category ? (in_array($gender->gen_id, $array_category_gender_id) ? 'selected' : '') : '') }}>{{ $gender->gen_name }}</option>
    @endforeach
</select>

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试一下

$category = Category::find($id);

$category_gen = $category->cte_gender_id;

$genders = Geslacht::where("gen_id", $gender_id)->get();
return view('your_view',compact('category_gen','gender'));
@foreach($genders as $gender)
@if($category_gen==$gender->gen_id)
        <option value="{{ $gender->gen_id }}" selected>{{ $gender->gen_name }}</option>
@else
option value="{{ $gender->gen_id }}">{{ $gender->gen_name }}</option>
@endif
@endforeach