Php 批量插入时的Laravel保存事件
Iam使用以下命令以块的形式批量插入大型数据库:Php 批量插入时的Laravel保存事件,php,laravel,Php,Laravel,Iam使用以下命令以块的形式批量插入大型数据库: DB::table($table)->insert($chunk); 但我想要的是在实际的insert操作之前,我想要能够修改每个表的$chunk数组,以添加/删除进入数据库的某些属性。为此,我在模型中设置保存事件: public static function boot() { parent::boot(); static::saving(function ($model) { Log::info('s
DB::table($table)->insert($chunk);
但我想要的是在实际的insert
操作之前,我想要能够修改每个表的$chunk
数组,以添加/删除进入数据库的某些属性。为此,我在模型中设置保存事件:
public static function boot()
{
parent::boot();
static::saving(function ($model) {
Log::info('saving');
return true;
});
}
但是,事件似乎不适用于Model::insert
操作
谁能告诉我怎样才能做到这一点
PS:我不能使用save()
(虽然保存事件也可以)方法,因为它只允许我一次保存一条记录,而我需要对每个块进行大容量插入
谢谢在这种情况下,您必须创建自己的事件/列表
大概是这样的:
$chunk = ['hello old world'];
event(new App\Events\SomeEventName($chunk));
dd($chunk);
DB::table($table)->insert($chunk);
php artisan make:event SomeEventName
//App\Events\SomeEventName
class SomeEventName extends Event
{
use SerializesModels;
public $chunk;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(&$chunk)
{
$this->chunk = &$chunk;
}
}
然后创建侦听器(您可以根据创建单独的文件)或将其放在引导模型方法中
\Event::listen('App\Events\SomeEventName', function($event) {
$event->chunk = ['hello new world']; // this will replace the old chunk
});
然后像这样使用它:
$chunk = ['hello old world'];
event(new App\Events\SomeEventName($chunk));
dd($chunk);
DB::table($table)->insert($chunk);
在这种情况下,您必须创建自己的事件/列表
大概是这样的:
$chunk = ['hello old world'];
event(new App\Events\SomeEventName($chunk));
dd($chunk);
DB::table($table)->insert($chunk);
php artisan make:event SomeEventName
//App\Events\SomeEventName
class SomeEventName extends Event
{
use SerializesModels;
public $chunk;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(&$chunk)
{
$this->chunk = &$chunk;
}
}
然后创建侦听器(您可以根据创建单独的文件)或将其放在引导模型方法中
\Event::listen('App\Events\SomeEventName', function($event) {
$event->chunk = ['hello new world']; // this will replace the old chunk
});
然后像这样使用它:
$chunk = ['hello old world'];
event(new App\Events\SomeEventName($chunk));
dd($chunk);
DB::table($table)->insert($chunk);