bhaveshdaswani / laravel-batch
在 Laravel 中插入和更新批量(批量)操作
v2.1.9
2020-05-20 09:50 UTC
This package is not auto-updated.
Last update: 2024-10-02 07:22:04 UTC
README
在 Laravel 中插入和更新批量(批量)操作
安装
composer require mavinoo/laravel-batch
服务提供者
在 app.php 文件中的 providers 数组中添加
Mavinoo\Batch\BatchServiceProvider::class,
别名
在 app.php 文件中的 aliases 数组中添加
'Batch' => Mavinoo\Batch\BatchFacade::class,
示例更新 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);
示例更新 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);
示例插入
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 )
辅助函数 batch()
// ex: update $result = batch()->update($userInstance, $value, $index); // ex: insert $result = batch()->insert($userInstance, $columns, $values, $batchSize);
测试
如果您在项目中没有安装 phpunit,首先运行 composer require phpunit/phpunit
在 Laravel 应用的根目录下,运行 ./vendor/bin/phpunit ./vendor/mavinoo/laravel-batch/tests