Как правильно сохранить в контроллере функцию в две отдельные таблицы - PullRequest
1 голос
/ 10 октября 2019

Я пытаюсь сохранить созданный мной элемент, у которого есть параметры, которые ему принадлежат, в моем случае это вопрос с параметрами, такими как параметры ответа. Вопрос сохраняется в его собственной таблице, а параметры находятся в отдельной таблице.

Это структура таблицы

Schema::create('survey_questions', function (Blueprint $table) {
    $table->increments('id');
    $table->string('question');
    $table->integer('survey_section_id')->unsigned();
    $table->integer('response_type_id')->unsigned();
    $table->boolean('optional');
    $table->timestamps();
    $table->foreign('survey_section_id')->references('id')->on('survey_sections');
    $table->foreign('response_type_id')->references('id')->on('response_types');
});

Schema::create('survey_question_options', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('survey_question_id')->unsigned();
    $table->string('option');
    $table->timestamps();
    $table->foreign('survey_question_id')->references('id')->on('survey_questions');
});

Отношения выглядят следующим образом

SurveyQuestionМодель

public function surveyQuestionOption()
{
    return $this->hasMany(SurveyQuestionOption::class);
}

SurveyQuestionOption Model

public function surveyQuestion()
{
    return $this->belongsTo(SurveyQuestion::class);
}

Это мой текущий метод хранения в контроллере

public function store(Request $request)
{
    DB::beginTransaction();
    $preg = new SurveyQuestion;
    $preg->question = $request->question;
    $preg->survey_section_id = $request->survey_section_id;
    $preg->response_type_id = $request->response_type_id;
    $preg->optional = $request->optional;
    $preg->save();

    if ($request->has('questionOptions')) {
        $questionOptions = [];
        $survey_question_id = $preg->id;

        foreach ($request->get('questionOptions') as $item) {
            $option = $item['option'];

            if (isset($option)) {
                $questionOptions[] = [
                    "survey_question_id" => $survey_question_id,
                    "option" => $option,
                ];
            }
        }
        if (count($questionOptions)) {
            SurveyQuestionOption::insert($questionOptions);
        }
    }

    $preg->save();

    DB::commit();
    return back();
}

Это мое обновление

public function update(Request $request, $id)
{
    DB::beginTransaction();
    $preg = SurveyQuestion::findOrFail($id);
    $preg->question = $request->question;
    $preg->survey_section_id = $request->survey_section_id;
    $preg->response_type_id = $request->response_type_id;
    $preg->optional = $request->optional;
    $preg->save();

    $ids = [];
    if (!empty($request->get('questionOptions'))) {
        foreach ($request->get('questionOptions') as $item) {
            $opt = SurveyQuestionOption::where('survey_question_id', $preg->id)->first();

            if (empty($opt)) {
                $opt = new SurveyQuestionOption();
                $opt->survey_question_id = $preg->id;
            }
            $opt->option = $item['option'];
            $opt->save();
        }
    }

    if (count($ids) > 0) {
        SurveyQuestionOption::whereNotIn('id', $ids)->delete();
    }

    $preg->save();

    DB::commit();
    return back();
}

Когда я пытаюсь сэкономить на vue, это не выдает никаких ошибок, но также не сохраняется в таблице survey_question_option. Я не совсем уверен, что моя ошибка на стороне контроллера или на стороне vue.

...