gpt4 book ai didi

php - 监听模型事件时无限循环

转载 作者:行者123 更新时间:2023-12-01 22:20:39 24 4
gpt4 key购买 nike

我有一个用于 Properties 的 Laravel 应用程序,比方说我在代码中的某处:

$property = new Property();
$property->city = "New York";
...
$property->save();

然后我有监听特定事件的事件监听器:

$events->listen(
'eloquent.saved: Properties\\Models\\Property',
'Google\Listeners\SetGeoLocationInfo@fire'
);

最后在 SetGeoLocationInfo.php 我有

public function fire($event)
{
$property = $event;
...
//get GPS data from Google Maps

$property->latitude = $googleMapsObject->latitude;
$property->longitude = $googleMapsObject->longitude;
$property->save();
}

当我将模型保存到无限递归时,因为在处理程序中调用了 save()

我如何更改我的代码以使其在保存后仅填充一次位置数据并避免递归?

我不能使用 flushEventListeners() 因为在这种情况下其他监听器停止工作(例如属性照片附加)。

最佳答案

我也一样。在 Laravel 5.6 中,您可以简单地覆盖模型中的 finishSave() 函数:

protected function finishSave(array $options)
{
// this condition allow to control whenever fire the vent or not
if (!isset($options['nosavedevent']) or empty($options['nosavedevent'])) {
$this->fireModelEvent('saved', false);
}

if ($this->isDirty() && ($options['touch'] ?? true)) {
$this->touchOwners();
}

$this->syncOriginal();
}

然后你可以像这样使用它:

public function fire($event)
{
$property = $event;
...
//get GPS data from Google Maps

$property->latitude = $googleMapsObject->latitude;
$property->longitude = $googleMapsObject->longitude;
$property->save(['nosavedevent' => true]);
}

关于php - 监听模型事件时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40324111/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com