将数组值插入到 Laravel 中的数据库中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48128471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert array values into database in laravel
提问by Rashed Hasan
I have 8 different questions that are coming from the database randomly.
我有 8 个不同的问题,这些问题随机来自数据库。
Now I want to insert the question_id
, user_id
and en_answer
into en_answers
table.
现在我想将question_id
,user_id
和en_answer
插入en_answers
表中。
Data was inserted, but here is some error like - the first one is, it's inserting only one-row value and the second one is, the question id is not correct.
数据已插入,但这里有一些错误,例如 - 第一个是,它只插入一行值,第二个是,问题 ID 不正确。
I tried something like bellow. Would someone please help to correct the controller method -
我试过类似波纹管的东西。有人可以帮忙纠正控制器方法 -
In index.blade.php-
在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>
In my controller-
在我的控制器中-
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');
}
回答by Alexey Mezenin
You're inserting into DB just one answer, the last one. Also, you can prepare the data and insert all the answers with just one query:
您插入数据库只是一个答案,最后一个。此外,您可以准备数据并通过一个查询插入所有答案:
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');
}