technote/laravel-transaction-fire-event

控制事务中发生的事件

v0.3.6 2022-07-13 15:13 UTC

This package is auto-updated.

Last update: 2024-09-15 21:18:39 UTC


README

CI Status codecov CodeFactor License: MIT PHP: >=7.4

用其他语言阅读: 英文日语.

控制事务中发生的事件。

Packagist

目录

详细信息

安装

composer require technote/laravel-transaction-fire-event

用法

  1. 在您想要控制事件触发的模型中,使用 DelayFireEvent 特性。

    <?php
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use Technote\TransactionFireEvent\Models\DelayFireEvent;
    
    class Item extends Model
    {
        use DelayFireEvent;
    
        public static function boot()
        {
            parent::boot();
    
            self::saved(function ($model) {
                //
            });
        }
    
        // relation example
        public function tags(): BelongsToMany
        {
            return $this->belongsToMany(Tag::class);
        }
    }
  2. 如果在事务中调用,则 saveddeleted 事件将被保留,直到事务结束。

    DB::transaction(function () {
        $item = new Item();
        $item->name = 'test';
        $item->save();
        // The `saved` event will not be fired here yet.
    
        $item->tags()->sync([1, 2, 3]);
    }
    
    // The `saved` event is called at the end of the transaction,
    // so you can get the synchronized tags with `$model->tags()->sync`.

改变事件以保持触发

默认的目标事件是 saveddeleted
要更改它,重写 getDelayTargetEvents

protected function getDelayTargetEvents(): array
{
    return [
        'created',
        'updated',
        'saved',
        'deleted',
    ];
}

作者

GitHub (Technote)
博客