I have fetched few records using JOIN then output taken in array. I am trying to put those records in another table using insertOrIgnore() and implode(). Below is the piece of code I have written: Code:
$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))
]);
Error: Columns are not being recognized.
SQLSTATE[42703]: Undefined column: 7 ERROR: column "0" of relation "Students_details" does not exist LINE 1: insert into "Students_details" ("0") values ($1) on conflict do... ^ (SQL: insert into "Students_details" ("0") values ([ 'id' => '3', 'contact' => 232453876 ], [ 'id' => 'Mark', 'contact' => 567085643 ]) on conflict do nothing)
It looks like you're over complicating things. InsertIgnore
either takes an array of key/value pairs or an array of arrays of key/value pairs so you don't need to create a string representation of the array and then implode it.
The code you have at the minute won't create a nested array of key/value pairs so it's going to assume that the numeric key for the array is actually the column name and the value for that column is the string version of the data.
If you want to keep the queries similar to what they are now you could do something like:
$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);