我有一个 Laravel 项目,我需要在保存模型并将一些数据附加到它之后立即进行一些计算。
在 Laravel 中调用 attach(或 detach / sync)后是否触发任何事件?
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
Laravel 5.8 现在在 ->attach() 上触发事件。
请参阅:https://laravel.com/docs/5.8/releases
并搜索:Intermediate Table / Pivot Model Events
https://laracasts.com/discuss/channels/eloquent/eloquent-attach-which-event-is-fired?page=1
解决问题的步骤:
就是这样。我创建了一个已经完成上述步骤的包:https://github.com/fico7489/laravel-pivot
更新:
从 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]。dispatch()
不会触发任何事件。