Laravel大规模更新,仍然发生火灾

时间:2019-05-25 09:11:27

标签: laravel eloquent

如文档中所述,laravel不会在批量更新/插入/删除时触发事件。 https://laravel.com/docs/5.8/eloquent#events

它为此使用Builder,并且不会触发事件。

例如,是否有一种方法可以在大规模更新后仍然触发事件?我只需要查询生成器自己就可以提取所需的信息(出于日志目的)。

2 个答案:

答案 0 :(得分:1)

@Paolo在批处理请求上不会被归档,因为您必须对单个记录执行操作。.

Analytic::where('id', '>', 100)->get()->each(function($analytic) {
    $analytic->delete();
});

答案 1 :(得分:0)

实际上是可能的,但是您必须扩展Eloquent构建器,覆盖update / insert方法并将事件发送到那里。 只是在玩它而已...需要工作,但基本思路如下:

class Test extends Model
{
    protected $guarded = [];

    public $dispatchesEvents = [
        'saved' => SavedTest::class
    ];


    /**
     * INCLUDE this as a trait in your model.
     * Overwrite the eloquentBuilder.
     *
     * @param  \Illuminate\Database\Query\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder|static
     */
    public function newEloquentBuilder($query)
    {

        return new TestBuilder($query);
    }


}

扩展了雄辩的构建者...

class TestBuilder extends Builder
{

    /**
     * Update a record in the database and fire event.
     *
     * @param  array  $values
     * @return int
     */
    public function update(array $values)
    {

        // normal eloquent behavior.
        $result =$this->toBase()->update($this->addUpdatedAtColumn($values));

        /*
         * Fire event.
         */
        if($result){
            if( $event = Arr::get($this->model->dispatchesEvents,'saved')){

                 // at the attributes.
                $this->model->fill($this->addUpdatedAtColumn($values));

                $queryBuilder =$this->toBase();

                event(new $event($this->model,$queryBuilder));
            }

        }

    }

    public function insert(array $values)
    {

       // same idea..
    }
}

事件类:

class SavedTest
{
    use SerializesModels;
    public $model;
    public $query;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($model,$query =null)
    {
        $this->model = $model;
        $this->query = $query;
    }


}

听众。

class SavedTestEvent
{


    /**
     * Create the event listener.
     *
     * 
     */
    public function __construct()
    {

    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {

        // The model , with the attributes.
        dump($event->model);

       // the query builder , you could extract the wheres or whatever to build your own log for it.
      dump($event->query); 


    }
}