laravel - 如何正确更新只有一个标识 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();
}
解决方案
基本上,当你使用 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,因为您没有指定将其保存在集合的哪个实例中。
推荐阅读
- r - 将列表和数据框转换为 DATAFRAME
- android - TextView 动态宽度,末尾有一个视图
- sql - 在 BigQuery 中使用 partition by 语句复制列值
- android - 如何从类中获取片段的变量?
- amazon-web-services - CloudWatch 警报操作仅触发一次 SNS
- android - Firebase 实时数据库中的分页
- javascript - 如何从地图函数内部更改组件以做出反应?
- python - 在 Django Web 应用程序中为租户设置子域?
- mysql - 必须是一条 SQL 语句,必须获取每个服务员月的事件、销售和参加者计数,但不使用迭代
- android - 发送多个数据的问题(数据通过节点 js 从 mongodb 传递到 Android)