雄辩的附加/分离/同步触发任何事件?
我有一个laravel项目,我需要在保存模型后立即进行一些计算并附加一些数据。
在调用 attach(或 detach/sync)后,是否有任何事件在 laravel 中触发?
我有一个laravel项目,我需要在保存模型后立即进行一些计算并附加一些数据。
在调用 attach(或 detach/sync)后,是否有任何事件在 laravel 中触发?
不,在《雄辩》中没有关系事件。但你可以很容易地自己做(例如给定的关系):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 对象的情况下执行此操作,但这种方式更方便,更灵活,而且更好。
解决问题的步骤:
仅此而已。我创建了已经这样做的软件包:https://github.com/fico7489/laravel-pivot