在我看来,我已经将输入选择循环并传递给控制器,以便我可以将它附加到我的数据透视表:
查看
{!! Form::open(['url'=>'surveys/'.$survey_id.'/persons/'.$person_id]) !!}
@foreach($questions as $question)
<ol>{{ $question->description }}</ol>
<select name="answers[]">
<option value=""></option>
@foreach($answers as $answer)
@if($answer->question_id == $question->id)
<option value="{{ $answer->question_id }}">{{ $answer->answer }}</option>
@endif
@endforeach
</select>
@endforeach
{!! Form::submit('submit',['class'=>'btn btn-primary']) !!}
{!! Form::close() !!}
CONTROLLER
$input = Request::input('answers');
$person = Person::findOrFail($person_id);
$check_if_existing = $person->answers()->find($person_id);
if (empty($check_if_existing))
{
foreach($input as $answer)
{
$person->answers()->attach($answer);
}
}else{
$person->answers()->updateExistingPivot($person_id,$input);
}
我使用 Request :: input('answers'); 获取数组。 Attache功能运行良好,但更新很糟糕。你能救我吗?
答案 0 :(得分:0)
您需要做的只是使用sync
代替attach
:
Person::findOrFail($person_id)->answers()->sync(Request::input('answers'));
无需循环,sync
接受id
的数组(包括其他值)。所以,只有一行代码就足够了。