laravel 7 将对象数组插入数据库
laravel 7 insert array of objects to db
这是我的数据
answers: [
{text: "dsfdsfjds", correct: "false"}
{text: "asjdkjsa", correct: "true"}
{text: "sadasdsad", correct: "false"}
}
我试过的
$answers[] = $request->answers;
$question = Question::create([
'question' => $request->question,
'date' => $request->date
]);
if($question) {
foreach($answers as $ans) {
$anss = Answer::create([
'question_id' => $question->id,
'text' => $ans->correct,
'correct' => $ans->correct,
]);
}
}
我收到这个错误
Trying to get property 'correct' of non-object"
请指导我如何将数据插入数据库。
我猜你的问题出在这一行:
$answers[] = $request->answers;
删除括号并重试:
$answers = $request->answers;
根据您的描述,我假设 answers 是一个 json 对象数组。您应该解码 json 对象以访问其 属性。在foreach循环的开头添加这个
$json_decoded_answer = json_decode($ans);
然后你可以这样做
$anss = Answer::create([
'question_id' => $question->id,
'text' => $json_decoded_answer->correct,
'correct' => $json_decoded_answer->correct,
]);
Trying to get property 'correct' of non-object"
尝试这样做
$answers = $request->answers;
$question = Question::create([
'question' => $request->question,
'date' => $request->date
]);
if($question) {
foreach($answers as $ans) {
$anss = Answer::create([
'question_id' => $question->id,
'text' => $ans['text'],
'correct' => $ans['correct'],
]);
}
}
我只是将这个 $answer[]
更改为 $answer
并使用了一个数组而不是对象
这是我的数据
answers: [
{text: "dsfdsfjds", correct: "false"}
{text: "asjdkjsa", correct: "true"}
{text: "sadasdsad", correct: "false"}
}
我试过的
$answers[] = $request->answers;
$question = Question::create([
'question' => $request->question,
'date' => $request->date
]);
if($question) {
foreach($answers as $ans) {
$anss = Answer::create([
'question_id' => $question->id,
'text' => $ans->correct,
'correct' => $ans->correct,
]);
}
}
我收到这个错误
Trying to get property 'correct' of non-object"
请指导我如何将数据插入数据库。
我猜你的问题出在这一行:
$answers[] = $request->answers;
删除括号并重试:
$answers = $request->answers;
根据您的描述,我假设 answers 是一个 json 对象数组。您应该解码 json 对象以访问其 属性。在foreach循环的开头添加这个
$json_decoded_answer = json_decode($ans);
然后你可以这样做
$anss = Answer::create([
'question_id' => $question->id,
'text' => $json_decoded_answer->correct,
'correct' => $json_decoded_answer->correct,
]);
Trying to get property 'correct' of non-object"
尝试这样做
$answers = $request->answers;
$question = Question::create([
'question' => $request->question,
'date' => $request->date
]);
if($question) {
foreach($answers as $ans) {
$anss = Answer::create([
'question_id' => $question->id,
'text' => $ans['text'],
'correct' => $ans['correct'],
]);
}
}
我只是将这个 $answer[]
更改为 $answer
并使用了一个数组而不是对象