我正在尝试使用 updateOrInsert()
方法批量插入和更新。但我收到数组到字符串对话错误(通过捕获)。有什么想法请告诉。谢谢。
$arr = [];
for ($i=0; $i < count($request->data); $i++) {
$arr[] = [
'month' => $request->End_month,
'year' => $request->start_Year,
'data' => str_replace(',' ,'', $request->data[$i]),
'cats' => $request->cat[$i],
'created_by'=> $this->createdBy()
];
} //end for
try {
DB::table('total_ports')->updateOrInsert(
['year' => $request->start_Year], $arr
);
return redirect()->back()->with('successmsg', 'Lorem ipsum');
} catch (Exception $e){
return $e->getMessage();
}
最佳答案
看:
https://laravel.com/api/master/Illuminate/Database/Query/Builder.html#method_updateOrInsert
在您的代码中,您将多维数组传递到第二个参数(而不是单维数组)。该函数将将该数组视为
[['key' => 'value'], ['key' => 'value'], ['key' => 'value'], ['key' => 'value']];
然后它将获取每个单独的内部数组并尝试将它们解释为列/字段名称。所以它试图将 ['key' => 'value']
转换为字符串。对于更新,您需要一次进行一项更新,除非您尝试一次更改多行。在这种情况下,您可以结合使用 where() 和 update()
关于php - 使用 updateOrInsert() 方法批量插入/更新并将数组转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57659665/