У меня есть форма, которая сохраняет структурированные данные в разделы, и у меня возникла сложная ситуация, когда я хочу редактировать эти поля. Форма имеет динамические c поля, так что вы можете добавить любое количество разделов и полей внутри каждого раздела. У меня есть главная таблица, в которой хранятся «подпрограммы», которые могут иметь несколько «разделов», а в них может быть несколько записей «упражнений». Сейчас мое решение состоит в том, чтобы удалить текущие записи и сохранить все как совершенно новую подпрограмму.
public function update(Request $request, $id)
{
$user = auth()->user();
$user->routines()->whereId($id)->delete();
$requestArr = $request->all();
$routine = new Routine();
$routine->user_id = auth()->user()->id;
$routine->name = $requestArr['name'];
$routine->description = $requestArr['description'];
$routine->save();
$routine_id = $routine->id;
foreach($requestArr['sections'] as $item){
$section = new Section();
$section->name = $item['name'];
$section->description = $item['description'];
$section->routine_id = $routine_id;
$section->save();
$section_id = $section->id;
if( array_key_exists( 'exercises', $item ) ){
foreach($item['exercises'] as $item2){
$exercise = new Exercise();
$exercise->name = $item2['name'];
$exercise->description = $item['description'];
$exercise->duration = 60;
$exercise->duration_unit = 'seconds';
$section->exercises()->save($exercise);
}
}
}
return redirect('/routines');
}
Я уверен, что есть более «элегантный» способ сделать это.
Мои миграции : Подпрограммы:
Schema::create('routines', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('name');
$table->string('description');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
Разделы:
Schema::create('sections', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('routine_id');
$table->string('name');
$table->string('description');
$table->timestamps();
$table->foreign('routine_id')
->references('id')
->on('routines')
->onDelete('cascade');
});
Упражнения:
Schema::create('exercises', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('description');
$table->integer('duration');
$table->string('duration_unit');
$table->timestamps();
});
Подпрограммы - один ко многим - Разделы Разделы - многие ко многим - Упражнения (я иметь среднюю таблицу упражнений)
Итак, мой вопрос, как я могу обновить записи, не удаляя текущие? Поскольку в случае добавления новых разделов / упражнений должны выполняться только эти вставки, просто отдыхайте -> update ();