首页 > 解决方案 > 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"

请指导我如何将数据插入数据库。

标签: laravellaravel-7

解决方案


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并使用了一个数组而不是对象


推荐阅读