我有一个模型的updating
方法的模型事件。
Hotel::updating(function($hotel) {
// Update cache
$hotel->q = $hotel->country->name . " " . $hotel->destination->name;
});
如果我使用eloquent.
保存()一个对象,效果会很好。然而,我想写一个工匠任务,为表中的每个行更新该字段。如何为表中的每一行触发模型事件?
我尝试使用Event::fire('eloquent.updating', function(Hotel::self);
之类的东西,因为模型事件是基于常规事件的。然而,这抛出了一个错误。
你是正确的,模型确实触发了eloquent.updating
事件。但是,为了允许事件调度程序为正确的模型触发事件,需要将模型名称附加到事件名称空间中。这是用来触发模型事件的代码:
protected function fireModelEvent($event, $halt = true)
{
if ( ! isset(static::$dispatcher)) return true;
// We will append the names of the class to the event to distinguish it from
// other model events that are fired, allowing us to listen on each model
// event set individually instead of catching event for all the models.
$event = "eloquent.{$event}: ".get_class($this);
$method = $halt ? 'until' : 'fire';
return static::$dispatcher->$method($event, $this);
}
您的模型事件实际上是:eloquent.updating: Hotel
。这自然意味着模型正在使用相同的语法进行侦听。
只是好奇,为什么你需要手动触发事件?您可以在一个工匠任务中使用模型本身来为您启动它们。