Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 批量插入时的Laravel保存事件_Php_Laravel - Fatal编程技术网

Php 批量插入时的Laravel保存事件

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

Iam使用以下命令以块的形式批量插入大型数据库:

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