批量插入时的Laravel Saving事件 [英] Laravel Saving event in case of bulk-insert

查看:97
本文介绍了批量插入时的Laravel Saving事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下命令将Iam批量插入大块数据库中:

Iam bulk-inserting large database in chunks with this command:

DB::table($table)->insert($chunk);

但是我想在实际的insert操作之前,我希望能够为每个表修改$chunk数组以添加/删除进入数据库的某些属性.为此,我在模型中设置了saving事件:

But want I want is before actual insert operation, I want to be able to modify $chunk array for each table to add/remove certain attributes going into database. In order to do so, I setup saving event in my model:

public static function boot()
{
    parent::boot();

    static::saving(function ($model) {
        Log::info('saving');
        return true;
    });
}

但是,似乎事件对于Model::insert操作不起作用.

However, it seems events don't work for Model::insert operations.

任何人都可以告诉我如何实现这一目标吗?

Can anybody tell how can I achieve this ?

PS:我不能使用save()(尽管可以使用保存事件)方法,因为它只允许我一次保存一个记录,而我需要对每个块进行批量插入.

PS: I can't use save() (though saving event would work with it) method as it would only allow me to save one record at a time whereas I need to do bulk insert of each chunk.

谢谢

推荐答案

在这种情况下,您必须创建自己的事件/监听器.

In this case you have to create your own Event/Listner.

类似这样的东西:

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;
    }
}

然后,使您成为监听器(您可以根据创建一个单独的文件laravel docs )或仅将其放在启动Model方法上

Then you make your listener (you can create a separate file according to laravel docs) or just put it on boot Model method

\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);

这篇关于批量插入时的Laravel Saving事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆