laravel - laravel 7将对象数组插入数据库
问题描述
这是我的数据
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"
请指导我如何将数据插入数据库。
解决方案
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
并使用了一个数组而不是对象
推荐阅读
- pki - rsconnect(和 PKI 安装)失败
- git - 如何仅在对主分支的拉取请求时运行管道
- pipe - 将 whos 命令的结果通过管道传输到 tlist
- mysql - 更新 MySQL 返回受影响的行,但实际上并没有更新数据库 [ nodejs mysql2 ]
- java - 得到“无法检查可用内存”。在 Oracle DB 18c 上
- java - Java Spring如何通过继承另一个接口的接口注入依赖关系?
- sqlkata - 如何使用 SqlKata 显示 SQL Server 数据库中的表?
- javascript - 有没有办法将用户输入作为电子邮件发送?
- algorithm - 检测图像/标签中的重叠组件
- ruby-on-rails - Rails 在使用 distinct 删除重复记录时出错