如何使用Laravel在数据库中插入数据数据及其各自的数据数组?

时间:2017-12-21 18:27:29

标签: php arrays laravel

问题模型

public function answer() {
    return $this->hasOne('App\Answer');
}

查看:

@foreach($questions as $question)
    <label>{{$question->question}}</label>
    <input type="hidden" name="question_ids[]" value="{{$question->id}}">
    <textarea name="answers[]"></textarea>           
@endforeach

控制器:

foreach($request->input('question_ids') as $id) {
    foreach($request->input('answer') as $ans) {
        $answer = new Answer;
        $question = Question::find($id);
        $answer->answer = $ans;
        $question->answer()->save($answer);
    }
}

我想插入问题及其各自的答案,但它正在插入相同问题的答案。请任何人帮忙。提前谢谢。

2 个答案:

答案 0 :(得分:0)

您可以将textarea答案字段设为数组,其中包含填充了问题ID的键。

@foreach($questions as $question)
    <label>{{$question->question}}</label>
    <textarea name="answers[{{ $question->id }}]"></textarea>           
@endforeach

和控制器。根据我的喜好略微编辑。

foreach ($request->input('answers') as $questionId => $value) {
    if ($question = Question::find($questionId)) {
        $answer = new Answer;
        $answer->answer = $value;
        $answer->question_id = $questionId;
        $answer->save();
    }
}

答案 1 :(得分:0)

与@ Chay22相同,只是更短一些。

foreach ($request->input('answers') as $questionId => $value) {
    if ($question = Question::find($questionId)) {
        $question->answer()->save(
             new Answer(['answer' => $value])
        );
    }
}

请注意answer模型的fillable数组中Answer。{/ p>