Laravel 批量插入、更新数据操作

在Laravel中 批量操作数据可以使用下面方法。

使用composer安装laravel-batch 文件。

composer require mavinoo/laravel-batch

composer下载安装完之后在config/app.php里面添加如下配置文件:

<?php

return [
     ......
     ......
     ......
     'providers' => [
         ......
         Mavinoo\Batch\BatchServiceProvider::class, //Laravel BATCH (BULK)
      ],
     'aliases' => [
         ...... 
         'Batch' => Mavinoo\Batch\BatchFacade::class, //Laravel BATCH (BULK)
     ],
]

使用方法:

batch()->update($channelInstance, $value, $index);

$channelInstance :代表模型对象

$value: 要更新的数组数据

$index:代表该表的唯一自增主键字段

 $newOrder = [];
 foreach ($order as $key => $item) {
       $newOrder[$key]['id']           = $item['channel_id'];
       $newOrder[$key]['total_amount'] = $item['total_amount'];
       $newOrder[$key]['updated_at']   = Date('Y-m-d H:i:s');
  }

    $index = 'id';
    //批量更新渠道的销售额
    $channelInstance = new Channel;
    Batch()->update($channelInstance, $newOrder, $index);
  

参考:https://github.com/mavinoo/laravelBatch