Я пытаюсь сохранить вопрос с опциями, эти опции сохраняются в другой таблице, чем сам вопрос.
Это мой контроллер
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->get('questionOptions')) {
$options = [];
$preg_id = $preg->id;
foreach ($request->get('questionOptions') as $item) {
$option = $item['option'];
if (isset($survey_question_id, $option)) {
$options[] = [
"survey_question_id" => $preg_id,
"option" => $option
];
}
}
if (count($options)) {
SurveyQuestionOption::insert($options);
}
}
DB::commit();
return back();
}
Это таблицы
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->string('option');
$table->integer('survey_question_id')->unsigned();
$table->timestamps();
$table->foreign('survey_question_id')->references('id')->on('survey_questions');
});
Отношения идут так:
SurveyQuestion -> hasMany -> SurveyQuestionOption
SurveyQuestionOption -> belongsTo -> SurveyQuestion
По моему яиметь questionOptions
как массив с объектами внутри и настроить его так, потому что мне нужно, чтобы вопросы с опциями имели минимум два, и я отправляю его в методе отправки следующим образом
questionOptions: [
{
option: ''
},
{
option: ''
},
],
submit() {
this.$refs.form.validate((valid) => {
if (valid) {
this.loading = true;
this.$inertia.post(this.baseUrl, {
question: this.form.question,
survey_section_id: this.form.survey_section_id,
response_type_id: this.form.response_type_id,
optional: this.form.optional,
questionOptions: this.form.questionOptions
}).then(
() => {
this.survey_question = this.$page.survey_question;
this.$message({
type: 'success',
message: 'Creado correctamente.'
});
this.loading = false
},
(res) => {
this.$message.error(parseError(res)[0]);
this.loading = false;
})
}
} else {
return false;
}
this.reset();
});
},
Причина, по которой я это делаю, заключается в том, что некоторые вопросы не имеют этих параметров, только у 1/4 они есть, поскольку это зависит от выбранного типа ответа. Но это не спасает его. Любая помощь приветствуется.