I came across a method of fast bulk update in mySQL recently:
The slow way:
UPDATE `example` SET `name` = 'Mary', `age` = '20' WHERE id = 2;
UPDATE `example` SET `name` = 'Nancy', `age` = '30' WHERE id = 4;
UPDATE `example` SET `name` = 'Oliver', `age` = '40' WHERE id = 5;
The fast way:
UPDATE `example` SET
`name` = ELT(FIELD(id,2,4,5),'Mary','Nancy','Oliver') ,
`age` = ELT(FIELD(id,2,4,5),'20','30','40')
WHERE id IN (2,4,5);
According to my google searching, the fast way is 50 times faster at large scale than the slow way, so I am wondering whether Laravel support this type of bulk update without the need to execute raw sql generated by myself.
Also if anyone is familiar with mysql and can tell me is this really that much faster or not, and if there is any scenario this method is actually worse I will be very graceful.
Edit(as requested in comment):
My current Laravel code would work like this for update:
foreach ($modelList as $model) {
$model->setConnection($connection);
$model->save();
}
What I would like for bulk update is
DB::connection($connection)->table($table)->bulkUpdate($models);
As I know currently Laravel already supports bulk insert as follows:
foreach ($models as $model) {
$attributes = $model->getAttributes();
$params[] = $attributes;
}
DB::connection($connection)->table($table)->insert($params);
which will generate one insert statement with multiple records instead of multiple insert statements.