繁体   English   中英

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

[英]Eloquent attach/detach/sync fires any event?

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

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

不,在 Eloquent 中没有关系事件。 但是你可以很容易地自己做(例如, 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 对象的情况下执行此操作,但这种方式更方便、更灵活且更简单。

解决您的问题的步骤:

  1. 创建自定义 BelongsToMany 关系
  2. 在 BelongsToMany 自定义关系中覆盖 attach、detach、sync 和 updateExistingPivot 方法
  3. 在覆盖方法中调度所需的事件。
  4. 覆盖模型中的belongsToMany() 方法并返回您的自定义关系而不是默认关系

就是这样。 我创建了已经这样做的包: https : //github.com/fico7489/laravel-pivot

Laravel 5.8 现在在 ->attach() 上触发事件

查看: https : //laravel.com/docs/5.8/releases

并搜索:中间表/枢轴模型事件

https://laracasts.com/discuss/channels/eloquent/eloquent-attach-which-event-is-fired?page=1

更新:

从 Laravel 5.8 Pivot 模型事件像普通模型一样被调度。

https://laravel.com/docs/5.8/releases#laravel-5.8

您只需要将using(PivotModel::class)添加到您的关系中,事件将在 PivotModel 上起作用。 Attach($id)将调度 Created 和 Creating

Detach($id)将调度 Deleting 和 Deleted,

Sync($ids)也会分派所需的事件 [Created,Creating,Deleting,Deleted]

只有没有 id 的dispatch()直到现在才分发任何事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM