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

dgjrabp2  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(313)

我有8个不同的问题,是来自数据库随机。
现在我要插入 question_id , user_id 以及 en_answer 进入 en_answers table。
数据被插入,但是这里有一些错误,比如-第一个是,它只插入了一行值,第二个是,问题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');

}
zu0ti5jz

zu0ti5jz1#

你只在db中插入了一个答案,最后一个。此外,只需一个查询即可准备数据并插入所有答案:

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');
}
k3bvogb1

k3bvogb12#

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

相关问题