雄辩的附加/分离/同步触发任何事件?

2022-08-30 19:00:22

我有一个laravel项目,我需要在保存模型后立即进行一些计算并附加一些数据。

在调用 attach(或 detach/sync)后,是否有任何事件在 laravel 中触发?


答案 1

不,在《雄辩》中没有关系事件。但你可以很容易地自己做(例如给定的关系):Ticket belongsToMany Component

// Ticket model
use App\Events\Relations\Attached;
use App\Events\Relations\Detached;
use App\Events\Relations\Syncing;
// ...

public function syncComponents($ids, $detaching = true)
{
    static::$dispatcher->fire(new Syncing($this, $ids, $detaching));

    $result = $this->components()->sync($ids, $detaching);

    if ($detached = $result['detached'])
    {
        static::$dispatcher->fire(new Detached($this, $detached));
    }

    if ($attached = $result['attached'])
    {
        static::$dispatcher->fire(new Attached($this, $attached));
    }
}

事件对象就这么简单:

<?php namespace App\Events\Relations;

use Illuminate\Database\Eloquent\Model;

class Attached {

    protected $parent;
    protected $related;

    public function __construct(Model $parent, array $related)
    {
        $this->parent    = $parent;
        $this->related   = $related;
    }

    public function getParent()
    {
        return $this->parent;
    }

    public function getRelated()
    {
        return $this->related;
    }
}

然后一个基本的听众作为一个合理的例子:

    // eg. AppServiceProvider::boot()
    $this->app['events']->listen('App\Events\Relations\Detached', function ($event) {
        echo PHP_EOL.'detached: '.join(',',$event->getRelated());
    });
    $this->app['events']->listen('App\Events\Relations\Attached', function ($event) {
        echo PHP_EOL.'attached: '.join(',',$event->getRelated());
    });

和用法:

$ php artisan tinker

>>> $t = Ticket::find(1);
=> <App\Models\Ticket>

>>> $t->syncComponents([1,3]);

detached: 4
attached: 1,3
=> null

当然,您可以在不创建 Event 对象的情况下执行此操作,但这种方式更方便,更灵活,而且更好。


答案 2

解决问题的步骤:

  1. 创建自定义属于多个关系
  2. 在 BelongsToMany 自定义关系覆盖附加、分离、同步和更新现有 Pivot 方法中
  3. 在重写方法中,调度所需的事件。
  4. 覆盖属于模型中的ToMany()方法,并返回您的自定义关系而不是默认关系

仅此而已。我创建了已经这样做的软件包:https://github.com/fico7489/laravel-pivot


推荐