nylontechnology/belongstomanywithevents

重写 Laravel Eloquent BelongsToMany 关系,以在 attach/detach 操作中触发事件

dev-master 2021-03-25 18:39 UTC

This package is not auto-updated.

Last update: 2024-09-26 00:24:45 UTC


README

重写 Laravel Eloquent BelongsToMany 关系,以在 attach/detach 操作中触发事件

安装

$ composer require nylontechnology/belongstomanywithevents

使用

  1. 导入到你的模型中
use NylonTechnology\BelongsToManyWithEvents as BelongsToMany;

class User extends Model {
....
  1. 在你的模型中,定义你想要观察的关系事件
class User extends Model {

    protected $observables = [
        'attached.roles',
        'detached.roles'
    ];

	public function roles()
	{
		return $this->belongsToMany('App\Role');
	}

	...
  1. 创建一个观察者,并根据你的需求处理事件
namespace App\Observers;

class ModelAuditObserver { 

    private function attached($observer_callback, $model, $ids) {}

		private function detached($observer_callback, $model, $ids) {}
		
		private function synced($observer_callback, $model, $ids) {}

		...
  1. 在 AppServiceProvider 的 boot() 方法中注册你的观察者
class AppServiceProvider extends ServiceProvider {

    public function boot() {
        App\User::observe(ModelAuditObserver::class);

    ...

注意事项

sync() 是 attach() 和 detach() 的包装器,所以通常你应该只观察 sync 事件或 attach/detach,除非你不介意冗余事件。

灵感来自 @andyberry88 的 gist