繁体   English   中英

在事件构造函数中传递模型对象时发生ModelNotFoundException

[英]ModelNotFoundException when passing Model Object in Event constructor

这是我的控制器:

$transaction = new ProductTransactionLog();
Event::fire(new SendResponseToProduct($response, $transaction));

这是事件类(SendResponseToProduct):

use Illuminate\Queue\SerializesModels;
use App\Models\ProductTransactionLog;

class SendResponseToProduct extends Event
{
    use SerializesModels;

    public $response = [];
    public $transaction;

    /**
     * Create a new event instance.
     */
    public function __construct($response = [], ProductTransactionLog $product_transaction)
    {
        // dd($transaction);
        $this->response = $response;
        $this->transaction = $product_transaction;
        // dd($this->transaction);
    }
}

这是在EventServiceProvider中:

protected $listen = [
        'App\Events\SendResponseToProduct' => [
            'App\Listeners\ResponseToProductListener',
        ],
    ];

当我运行控制器时,即当我触发事件时,我得到了这个奇怪的错误:

Handler.php第46行中的NotFoundHttpException:模型[App \\ Models \\ ProductTransactionLog]的无查询结果。

当我在Event构造函数中dd时,我得到了对象。 当我取消注释dd ,再次出现错误。

当我在Listener类中dd时,我得到了同样的错误。 它没有到达Listener类。

我在这里想念什么?

您正在使用SendResponseToProduct中的SerializesModels特征作为队列(可能是同步的)。 它总是序列化和反序列化所有字段。

此特性特别检查序列化字段(在此示例中为:public $ transaction;)是ModelIdentifier实例( Model对象的序列化字段为-因为Model类是QueueableEntity接口的实例)。 如果是,那么他试图通过id在DB中查找模型的记录,在这种情况下,您在该模型上没有该记录,因为您只是创建了没有任何数据的记录。

因此,您可以执行的操作是在不使用队列的情况下删除SerializesModels特质-或在此处不传递Empyt模型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM