【问题标题】:batch insert/update using updateOrInsert() method and getting Array to string conversion使用 updateOrInsert() 方法批量插入/更新并将数组转换为字符串
【发布时间】:2019-12-30 17:58:19
【问题描述】:

我正在尝试使用updateOrInsert() 方法进行批量插入和更新。但我得到数组到字符串对话错误(通过catch)。任何想法请告诉。谢谢。

$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();
}

【问题讨论】:

  • 哪部分代码抛出数组到字符串的转换错误?
  • updateOrInsert 方法中的第一个数组。
  • 如果我只使用插入方法,那么它就像 DB::table('total_ports')->insert($arr);

标签: php mysql laravel-5.8


【解决方案1】:

看看:

https://laravel.com/api/master/Illuminate/Database/Query/Builder.html#method_updateOrInsert

在您的代码中,您将多维数组传递给第二个参数(而不是一维数组)。这个函数会将该数组作为

[['key' => 'value'], ['key' => 'value'], ['key' => 'value'], ['key' => 'value']];

然后它将获取每个单独的内部数组并尝试将它们解释为列/字段名称。所以它试图将['key' =&gt; 'value'] 转换为字符串。对于您的更新,您需要一次执行一项,除非您尝试一次更改多行。在这种情况下,您将使用 where() 和 update() 的组合

【讨论】:

    猜你喜欢
    • 2017-04-03
    • 1970-01-01
    • 2020-05-16
    • 2021-05-15
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    相关资源
    最近更新 更多