Laravel: insertOrIgnore() 不接受数组作为输入

Laravel: insertOrIgnore() not accepting array as input

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

$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]: Undefined column: 7 ERROR: column "0" of relation "Students_details" does not exist LINE 1: insert into "Students_details" ("0") values () on conflict do... ^ (SQL: insert into "Students_details" ("0") values ([ 'id' => '3', 'contact' => 232453876 ], [ 'id' => 'Mark', 'contact' => 567085643 ]) on conflict do nothing)

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

您目前拥有的代码不会创建 key/value 对的嵌套数组,因此它将假定数组的数字键实际上是列名,该列的值为数据的字符串版本。

如果你想保持查询与现在类似,你可以这样做:

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