雄辩的连接/分离/同步会触发任何事件?

时间:2015-03-08 10:14:47

标签: php laravel eloquent

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

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

4 个答案:

答案 0 :(得分:25)

不,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 :(得分:9)

解决问题的步骤:

  1. 创建自定义BelongsToMany关系
  2. 在BelongsToMany自定义关系覆盖附加,分离,同步和updateExistingPivot方法
  3. 在重写方法中调度所需的事件。
  4. 覆盖Model中的belongsToMany()方法并返回自定义关系而非默认关系
  5. 就是这样。我创建了已经这样做的包:https://github.com/fico7489/laravel-pivot

答案 2 :(得分:1)

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

答案 3 :(得分:1)

更新

从Laravel 5.8枢轴模型开始,事件像普通模型一样被调度。

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

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

Detach($id)将分派“删除和删除”,

Sync($ids)也将调度所需的事件[创建,创建,删除,已删除]

只有dispatch()且没有id,直到现在才调度任何事件。