I'm currently using a make shift INSERT on DUPLICATE UPDATE function that relies on a DB raw query from eloquent. I'm looking to improve the quality of the code and the speed. Please take a look
function bulkInsertBookTable($data)
{
$inserts = [];
foreach ($data as $item) {
$inserts[] = implode(', ', ['"' . $item['book_id'] . '"', $item['isbn']]);
}
$inserts = Collection::make($inserts);
$inserts->chunk(500)->each(function($ch) {
$insertString = '';
foreach ($ch as $element) {
$insertString .= '(' . $element . '), ';
}
$insertString = rtrim($insertString, ", ");
try {
DB::insert("INSERT INTO book_datas (`book_id`, `isbn`) VALUES $insertString ON DUPLICATE KEY UPDATE `isbn`=VALUES(`isbn`)");
} catch (\Exception $e) {
print_r([$e->getMessage()]);
}
});
}
NOTE:
createOrUpdate
function is only valid on model level and does not allow mass insert. Doing Model::insert()
will allow to have a $data = []
inserted as long as fillable is used however it will reject if there is a duplicate key