我有一个 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对象,但这种方式更方便、更灵活、更简单。
关于php - Eloquent 附加/分离/同步触发任何事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28925292/