在 Laravel 中插入批量和更新批量
Insert and update batch (bulk) in laravel
composer require mavinoo/laravel-batch
File app.php in array providers:
Mavinoo\Batch\BatchServiceProvider::class,
File app.php in array aliases:
'Batch' => Mavinoo\Batch\BatchFacade::class,
…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);
// or
batch()->update($userInstance, $values, $index);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);
// or
batch()->update($userInstance, $values, $index);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);
// or
batch()->update($userInstance, $values, $index);…// result: false or array
sample array result:
Array
(
[totalRows] => 384
[totalBatch] => 500
[totalQuery] => 1
)Add HasBatch trait into model:
namespace App\Models;
use Mavinoo\Batch\Traits\HasBatch;
class User extends Model
{
use HasBatch;
}And call batchUpdate() or batchInsert() from model:
use App\Models\User;
// ex: update
User::batchUpdate($value, $index);
// ex: insert
User::batchInsert($columns, $values, $batchSize);// ex: update
$result = batch()->update($userInstance, $value, $index);
// ex: insert
$result = batch()->insert($userInstance, $columns, $values, $batchSize);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
USDT Address: 0x98410956169cdd00a43fe895303bdca096f37062
暂无开放 Issues,或尚未同步最近议题。