Laravel 内批量更新数据
推荐个好用的批量更新包 laravelBatch
GitHub 地址 https://github.com/mavinoo/laravelBatch
除了json 字段需要特殊注意下,其他字段更新用起来都很愉快
json 字段: 如果批量内也有json string 带有 \n 这种 在处理时候需要特殊注意下 需要替换为 \\n
否则入库会提示: Invalid Data
Laravel BATCH (BULK)
Insert and update batch (bulk) in laravel
Install
composer require mavinoo/laravel-batch
Service Provider
file app.php in array providers :
Mavinoo\Batch\BatchServiceProvider::class,
Aliases
file app.php in array aliases :
'Batch' => Mavinoo\Batch\BatchFacade::class,
Example Update 1
use App\Models\User;
$userInstance = new User;
$value = [
[
'id' => 1,
'status' => 'active',
'nickname' => 'Mohammad'
] ,
[
'id' => 5,
'status' => 'deactive',
'nickname' => 'Ghanbari'
] ,
];
$index = 'id';
Batch::update($userInstance, $value, $index);
Example Update 2
use App\Models\User;
$userInstance = new User;
$value = [
[
'id' => 1,
'status' => 'active'
],
[
'id' => 5,
'status' => 'deactive',
'nickname' => 'Ghanbari'
],
[
'id' => 10,
'status' => 'active',
'date' => Carbon::now()
],
[
'id' => 11,
'username' => 'mavinoo'
]
];
$index = 'id';
Batch::update($userInstance, $value, $index);
Example Increment / Decrement
use App\Models\User;
$userInstance = new User;
$value = [
[
'id' => 1,
'balance' => ['+', 500] // Add
] ,
[
'id' => 2,
'balance' => ['-', 200] // Subtract
] ,
[
'id' => 3,
'balance' => ['*', 5] // Multiply
] ,
[
'id' => 4,
'balance' => ['/', 2] // Divide
] ,
[
'id' => 5,
'balance' => ['%', 2] // Modulo
] ,
];
$index = 'id';
Batch::update($userInstance, $value, $index);
Example Insert
use App\Models\User;
$userInstance = new User;
$columns = [
'firstName',
'lastName',
'email',
'isActive',
'status',
];
$values = [
[
'Mohammad',
'Ghanbari',
'emailSample_1@gmail.com',
'1',
'0',
] ,
[
'Saeed',
'Mohammadi',
'emailSample_2@gmail.com',
'1',
'0',
] ,
[
'Avin',
'Ghanbari',
'emailSample_3@gmail.com',
'1',
'0',
] ,
];
$batchSize = 500; // insert 500 (default), 100 minimum rows in one query
$result = Batch::insert($userInstance, $columns, $values, $batchSize);
// result : false or array
sample array result:
Array
(
[totalRows] => 384
[totalBatch] => 500
[totalQuery] => 1
)
Helper batch()
// ex: update
$result = batch()->update($userInstance, $value, $index);
// ex: insert
$result = batch()->insert($userInstance, $columns, $values, $batchSize);
Tests
If you don’t have phpunit installed on your project, first run composer require phpunit/phpunit
In the root of your laravel app, run ./vendor/bin/phpunit ./vendor/mavinoo/laravel-batch/tests
Donate
BTC Address: 16XDxkcqiEJ8DYf4xWxu7WK3Peo29TvXxD
本作品采用《CC 协议》,转载必须注明作者和本文链接
最近有这方面的需求,先mark一下
这还挺好, 之前都是拼接原生sql用 case when更新,这样写实在是不方便。
有
updateOrInsert
方法吗?您好,我在使用
Batch::update($userInstance, $value, $index);
方法更新的时候总是报错提示Non-static method Mavinoo\\Batch\\Batch::update() cannot be called statically
。您又遇到这种情况吗支持自定义的case when 参数吗
请问可以支持多个字段查询更新吗?
Using $this when not in object context
大佬,使用报这个错误,是不是静态代理类没找到
看我的博客:数据库-批量更新