首页 > 解决方案 > 如何正确更新只有一个标识 ID 的数组

问题描述

我正在尝试使用类似这样的对象更新数组,使用当前代码我只保存第一个,我知道这是问题,但我不知道如何解决它

array (
    0 => 
    array (
      'option' => 'new',
    ),
    1 => 
    array (
      'option' => 'ewrwer',
    ),
  ),

这是我当前的代码,有问题的行是

$option = SurveyQuestionOption::where('survey_question_id', $preg->id)->first();

我该如何解决这个问题,以便它循环遍历数组中的所有内容,questionOptions而不仅仅是第一个?我试过->get(),但后来->save()不起作用。

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 ($request->get('questionOptions')) {
        foreach ($request->get('questionOptions') as $item) {
            $option = SurveyQuestionOption::where('survey_question_id', $preg->id)->first();

            if (empty($option)) {
                $option = new SurveyQuestionOption();
                $option->survey_question_id = $preg->id;
            }

            $option->option = $item['option'];
            $option->save();
        }
    }
    if (count($ids) > 0) {
        SurveyQuestionOption::whereNotIn('id', $ids)->where('survey_question_id', $preg->id)->delete();
        }

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

标签: laravel

解决方案


基本上,当你使用 get 时,你会得到一个集合,所以你不能真正使用 save 。你需要做一个 foreach 循环,并保存在其中。IE; 像这样;

$options = SurveyQuestionOption::where('survey_question_id', $preg->id)->get();
foreach($options as $option){
   if (empty($option)) {
      $option = new SurveyQuestionOption();
      $option->survey_question_id = $preg->id;
   }

   $option->option = $item['option'];
   $option->save();
}

请注意,如果您不使用 foreach 循环,则无法保存 $options,因为您没有指定将其保存在集合的哪个实例中。


推荐阅读