在laravel中将数组值插入数据库

时间:2018-01-06 14:43:53

标签: php mysql arrays laravel multidimensional-array

我有8个不同的问题来自数据库随机。现在我想将question_id,user_id和en_answer插入'en_answers'表中。插入了数据,但是这里有一些错误 - 第一个是,它只插入一个行值,第二个是,问题ID不正确。我试过像波纹管一样的东西。有人请帮助纠正控制器方法 - 在index.blade.php中

<form action="{{ url('en-question-answer') }}" method="POST">
       {{ csrf_field() }}
  <?php 
    $count=1;
  ;?>
  @foreach($equestions as $equestionType)
      @foreach($equestionType as $key => $equestion)
          <p>{{ $equestion->question }}</p>
          <input type="hidden" name="question_id[{{$count}}]" value="{{ $equestion->id }}">
          <label class="radio-inline">
           <input type="radio" name="en_answer[{{$count}}]" value="{{ $equestion->option1 }}">{{ $equestion->option1 }}
          </label>
           <label class="radio-inline">
           <input type="radio" name="en_answer[{{$count}}]" value="{{ $equestion->option2 }}">{{ $equestion->option2 }}
           </label>
             <hr>
    <?php $count++; ?>
       @endforeach
   @endforeach      
  <button type="submit" class="btn btn-primary btn-sm pull-right">Submit</button></form>

在我的控制器中 -

    public function store(Request $request, User $user){
    $user_id = Sentinel::getUser()->id;

    $answer = new EnAnswer;
    $answer->user_id     = $user_id;

    $data = Input::get();
    for($i = 1; $i < count($data['en_answer']); $i++) {
        $answer->en_answer     = $data['en_answer'][$i];
    }
    for($i = 1; $i < count($data['question_id']); $i++) {
        $answer->question_id     = $data['question_id'][$i];
    }

    //dd($answer);
    //return $answer;
    $answer->save();
    return redirect('submitted')->with('status', 'Your answers successfully submitted');

}

2 个答案:

答案 0 :(得分:4)

您只需将一个答案插入数据库,最后一个答案。此外,您只需一个查询即可准备数据并插入所有答案:

public function store(Request $request)
{
    for ($i = 1; $i < count($request->en_answer); $i++) {
        $answers[] = [
            'user_id' => Sentinel::getUser()->id,
            'en_answer' => $request->en_answer[$i],
            'question_id' => $request->question_id[$i]
        ];
    }
    EnAnswer::insert($answers);
    return redirect('submitted')->with('status', 'Your answers successfully submitted');
}  

答案 1 :(得分:0)

$answers = [];
for ($i = 0; $i < count($request->day); $i++) {
    $answers[] = [
        'day' => $request->day[$i],
        'from' => $request->from[$i],
        'to' => $request->to[$i]
    ];