检查 Laravel 延迟队列作业中传递的对象是否存在
Checking passed object existence in Laravel delayed queue job
我相信如果我将 Eloquent 对象传递给延迟的 Laravel 作业,则会调用 "findOrFail" 方法来 "restore" 对象并将其传递给我的工作 class.
问题是代表对象的数据库记录可能在作业实际处理时消失。
所以 "findOrFail" 在调用 "handle" 方法之前就中止了。
一切似乎都很好。问题是作业现在 "gets transferred" 到失败的作业列表。我知道我可以手动将其从那里删除,但这听起来不对。
有没有办法 "know" 在我的工作 class 中直接传递对象 "failed to load" 或 "does not exist" 或类似的东西?
基本上,如果在 "rebuilding" 我传递的对象时抛出 "ModelNotFoundException",我希望能够做一些事情。
谢谢
解决方案:
根据 Yauheni Prakopchyk 的回答,我编写了自己的特征并在我需要改变行为的地方使用它而不是 SerializesModels。
这是我的新特质:
<?php
namespace App\Jobs;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Database\ModelIdentifier;
use Illuminate\Database\Eloquent\ModelNotFoundException;
trait SerializesNullableModels
{
use SerializesModels {
SerializesModels::getRestoredPropertyValue as parentGetRestoredPropertyValue;
}
protected function getRestoredPropertyValue($value)
{
try
{
return $this->parentGetRestoredPropertyValue($value);
}
catch (ModelNotFoundException $e)
{
return null;
}
}
}
就是这样 - 现在,如果模型加载失败,我仍然会得到一个空值,并且可以在我的 handle 方法中决定如何处理它。
如果这只在工作 class 或两个工作中需要,我可以在其他任何地方继续使用原始特征。
如果我没记错的话,你必须在你的工作中覆盖 getRestoredPropertyValue
class。
protected function getRestoredPropertyValue($value)
{
try{
return $value instanceof ModelIdentifier
? (new $value->class)->findOrFail($value->id) : $value;
}catch(ModelNotFoundException $e) {
// Your handling code;
}
exit;
}
我相信如果我将 Eloquent 对象传递给延迟的 Laravel 作业,则会调用 "findOrFail" 方法来 "restore" 对象并将其传递给我的工作 class.
问题是代表对象的数据库记录可能在作业实际处理时消失。
所以 "findOrFail" 在调用 "handle" 方法之前就中止了。
一切似乎都很好。问题是作业现在 "gets transferred" 到失败的作业列表。我知道我可以手动将其从那里删除,但这听起来不对。
有没有办法 "know" 在我的工作 class 中直接传递对象 "failed to load" 或 "does not exist" 或类似的东西?
基本上,如果在 "rebuilding" 我传递的对象时抛出 "ModelNotFoundException",我希望能够做一些事情。
谢谢
解决方案:
根据 Yauheni Prakopchyk 的回答,我编写了自己的特征并在我需要改变行为的地方使用它而不是 SerializesModels。
这是我的新特质:
<?php
namespace App\Jobs;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Database\ModelIdentifier;
use Illuminate\Database\Eloquent\ModelNotFoundException;
trait SerializesNullableModels
{
use SerializesModels {
SerializesModels::getRestoredPropertyValue as parentGetRestoredPropertyValue;
}
protected function getRestoredPropertyValue($value)
{
try
{
return $this->parentGetRestoredPropertyValue($value);
}
catch (ModelNotFoundException $e)
{
return null;
}
}
}
就是这样 - 现在,如果模型加载失败,我仍然会得到一个空值,并且可以在我的 handle 方法中决定如何处理它。 如果这只在工作 class 或两个工作中需要,我可以在其他任何地方继续使用原始特征。
如果我没记错的话,你必须在你的工作中覆盖 getRestoredPropertyValue
class。
protected function getRestoredPropertyValue($value)
{
try{
return $value instanceof ModelIdentifier
? (new $value->class)->findOrFail($value->id) : $value;
}catch(ModelNotFoundException $e) {
// Your handling code;
}
exit;
}