【问题标题】:Laravel: insertOrIgnore() not accepting array as inputLaravel:insertOrIgnore() 不接受数组作为输入
【发布时间】:2020-04-12 20:37:15
【问题描述】:

我使用 JOIN 获取了几条记录,然后将输出放入数组中。 我正在尝试使用 insertOrIgnore() 和 implode() 将这些记录放在另一个表中。 下面是我写的一段代码: 代码:

$strSql =  DB::table('details')
                ->join("students", 'details.name', '=', 'students.name')
                ->select('details.id','students.contact')
                ->get();

foreach($strSql as $values){
    $arrValues[] = "[ 'id' =>  '$values->id', 'contact' => $values->contact ]";                            
}

DB::table('Students_details')->insertOrIgnore([
    (implode( ', ' , $arrValues))
]); 

错误: 无法识别列。

SQLSTATE[42703]:未定义列:7 错误:关系“Students_details”的列“0”不存在 第 1 行:在冲突时插入“Students_details”(“0”)值($1)... ^ (SQL: 插入 "Students_details" ("0") 值 ([ 'id' => '3', 'contact' => 232453876 ], [ 'id' => 'Mark', 'contact' => 567085643 ]) 在冲突中什么也不做)

【问题讨论】:

标签: php laravel lumen


【解决方案1】:

看起来你把事情复杂化了。 InsertIgnore 要么采用键/值对数组,要么采用键/值对数组,因此您无需创建数组的字符串表示然后将其内爆。

你现在的代码不会创建一个嵌套的键/值对数组,所以它会假设数组的数字键实际上是列名,而该列的值是字符串版本数据。

如果您想让查询与现在相似,您可以执行以下操作:

$results = DB::table('details')
    ->join("students", 'details.name', '=', 'students.name')
    ->select('details.id', 'students.contact')
    ->get()
    ->map(function ($item) {
        return (array)$item;
    })
    ->toArray();

DB::table('Students_details')->insertOrIgnore($results);

【讨论】:

  • 我仍然收到一个错误:传递给 Illuminate\Database\Query\Builder::insertOrIgnore() 的参数 1 必须是数组类型,给定对象你能帮我解决这个问题吗?
  • 需要$results->all()来获取集合的底层数组
  • 我的愚蠢错误@apokryfos。感谢您指出。我改用了toArray(),但它会给出相同的结果。
猜你喜欢
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2020-06-25
  • 2014-03-24
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
  • 2016-03-05
相关资源
最近更新 更多