Impregnated mass, INCLUDING DUPLICATE KEY UPDATE

I was doing:

$data = [ ['amodule'=>'amodule', 'akey'=>'first_example', 'avalue'=>'4096', 'created_at'=>'2014-09-21'], ['amodule'=>'amodule2', 'akey'=>'sec_example', 'avalue'=>'4097', 'created_at'=>'2014-09-22'], ['amodule'=>'amodule2', 'akey'=>'sec_example', 'avalue'=>'4097', 'created_at'=>'2014-09-22'], ]; Models\Snapshot::insert($data); 

Just do bulk insert. Now I want to add the ON DUPLICATE key to it. Any idea on how to do this? Or ignore duplicates in the list?

Thanks in advance...

+5
source share
1 answer

Eloquent does not support this at the moment, you will have to write it as a raw request.

 // generates (?,?,?,?),(?,?,?,?),(?,?,?,?),(?,?,?,?) $valueString = implode(',', array_fill(0, count($data), '(' . implode(',', array_fill(0, count($data[0]), '?')) . ')')); $values = []; // Flattens the array foreach($data as $row) { foreach($row as $value) { $values[] = $value; } } // Perform the insert \DB::insert( "insert into `snapshots` (`amodule`, `akey`, `avalue`, `created_at`) values {$values} on duplicate key update", $values ); 

Keep in mind that to run on duplicate key update , at least one of the inserted values ​​must have a primary key or a unique key.

+1
source

Source: https://habr.com/ru/post/1203334/


All Articles