technote / laravel-transaction-fire-event
控制事务中发生的事件
v0.3.6
2022-07-13 15:13 UTC
Requires
- php: ^7.4|^8.0
- laravel/framework: *
Requires (Dev)
- codedungeon/phpunit-result-printer: ^0.32.0
- dealerdirect/phpcodesniffer-composer-installer: ^0.7.2
- fakerphp/faker: ^1.19
- orchestra/testbench: ^6.24
- phpmd/phpmd: ^2.12
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: ^3.7
README
控制事务中发生的事件。
目录
安装
composer require technote/laravel-transaction-fire-event
用法
-
在您想要控制事件触发的模型中,使用
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); } }
-
如果在事务中调用,则
saved
和deleted
事件将被保留,直到事务结束。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`.
改变事件以保持触发
默认的目标事件是 saved
和 deleted
。
要更改它,重写 getDelayTargetEvents
。
protected function getDelayTargetEvents(): array { return [ 'created', 'updated', 'saved', 'deleted', ]; }