在foreach循环中使用update方法更新Laravel



我想更新联系人的地址记录。但只有"$add"的最后一个值数组更新地址记录。

if ($this->contact::where('id', $id)->exists())
{ $new_request = $request->except(['address']);
$this->contact->where('id', $id)->update($new_request);
if ($request->has('address')) {
foreach ($request->address as $add) {
$this->address::where('contact_id', $id)->update($add);
}
}
} else {
return response()->json([
'message' => 'Record not found.'
], 404);
}

$this->address::where('contact_id', $id)->update($add);行将根据看起来是外键的contact_id更新所有行。因此,所有相关的行都将更新。

尝试在where子句中添加主键或添加唯一标识符。

最新更新