我想更新我的多条记录。但只有第一个记录正在更新,其他记录不是......
我使用fetch api进行ajax调用,但我问题不在这里,因为我能够发送数组数据,我可以在浏览器开发部分看到。 (我的意思是,我可以发送多个身份证数据,这没关系)
然后我试图将它们保存在foreach循环中,但只有第一条记录在此循环中更新。
控制器中的
public function approveComment(Request $request)
{
if ($request->ajax()) {
$ids = $request->json()->all();
foreach ($ids as $id) {
$comment = Comments::find($id);
$comment->comment_status = 1;
$comment->save();
}
return response()->json("successful");
} else {
$comment = Comments::find($request->input('comment_id'));
$comment->comment_status = 1;
$comment->save();
return back();
}
}
ajax call;
ajax.put('comments/approve',token,ids)
.then(data => data.json())
.then(log => console.log(log))
.catch(err => console.log(err))
把方法放在ajax类中
async put(url, token, data) {
const response = await fetch(url, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": token
},
method: "put",
credentials: "same-origin",
body: JSON.stringify(data)
});
return response;
}
答案 0 :(得分:0)
我发现了问题;
public function approveComment(Request $request)
{
if ($request->ajax()) {
$ids = $request->json()->all();
foreach ($ids as $id) {
$comment = Comments::find($id);
$comment->comment_status = 1;
$comment->save();
// return response()->json("successful"); (it was here)
}
return response()->json("successful"); (it should be in here, not in loop)
} else {
$comment = Comments::find($request->input('comment_id'));
$comment->comment_status = 1;
$comment->save();
return back();
}
}