quangpv/fast-bulk-update

fast bulk update in laravel

v1.0.1 2024-03-30 04:27 UTC

This package is auto-updated.

Last update: 2024-09-30 05:44:47 UTC


README

This package currently supports bulk updates in MySQL, MariaDB, and PostgreSQL, and it is compatible with Laravel version 8 and above


✔️ supports MySql
✔️ supports MariaDB
✔️ supports PostgreSQL

Laravel fast bulk update

Latest Stable Version Total Downloads Latest Unstable Version License PHP Version Require

Install

composer require quangpv/fast-bulk-update

Example Usage

use App\Models\User;

$model = App::make(User::class);

// If you wish to modify the database connection, you can set it on your model.
$model->setConnection('mariadb');
$model->setConnection('mysql');
$model->setConnection('pgsql');

$values = [
     [
         'id' => 1,
         'code' => 'UC01',
         'nickname' => 'quangpv'
     ] ,
     [
         'id' => 2,
         'code' => 'UC02',
         'nickname' => 'haiza'
     ] ,
];

// We will find the records by their IDs and update them.
$indexes = ['id']; // primary key
// $indexes = ['code', 'id']; // composite primary key

$updateFields = ['nickname']; // only update the field `nickname`
// $updateFields = []; // update all fields

$affectedRows = \BatchUpdate::execute($model, $values, $indexes, $updateFields);

Warning

Ensure that the indexes match the primary key in your table, because the MySQL database driver always uses the "primary" and "unique" indexes of the table to detect existing records.

Other option


If you wanna update on fields that are not primary or unique indexes, you can refer to my approach here
https://github.com/quanggpv/laravel-upsert-improved.

My idea


The basic update queries will use the 'INSERT...ON DUPLICATE KEY UPDATE...' statement in MYSQL.

I took inspiration from Laravel's 'upsert' function, but removed the 'insert' functionality. I believe the built-in function of MySQL has an excellent data structure for updating


Important

If this package has been helpful to you, please give me a star. Thank you! :D

References


https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html

https://laravel.com/docs/10.x/eloquent#upserts