使用工匠和在服务提供程序中实例化的对象时没有查询结果错误



我创建了一个提供类App\Path的服务提供程序。这是使用 $request->getPathInfo(( 通过 Eloquent 加载的

    $this->app->singleton(Path::class, function($app)
    {
        $request = $app->make(IlluminateHttpRequest::class);
        $path = Path::with(['template', 'parts'])->findOrFail($request->getPathInfo());
        return $path;
    });

该应用程序工作正常,符合预期。但是,当我想使用工匠时,出现以下错误:

In Builder.php line 369:
No query results for model [AppPath] /

这可以防止我清除缓存,创建模型等。似乎Laravel在运行任何工匠命令时运行register((,完成后,请求路径为"/",这在数据库中不存在。有没有更好的方法来填充 Path 对象?解决此问题的唯一方法似乎是为"/"添加一个虚拟记录。

您可以检查应用是否从控制台运行并调整其逻辑,例如:

$this->app->singleton(Path::class, function($app)
    {
        if ($app->runningInConsole()) {
          return null;
        }
        $request = $app->make(IlluminateHttpRequest::class);
        $path = Path::with(['template', 'parts'])->findOrFail($request->getPathInfo());
        return $path;
    });

最新更新