首页 > 解决方案 > 使用在服务提供者中实例化对象的工匠没有查询结果错误

问题描述

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

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

该应用程序运行良好,符合预期。但是,当我想使用 Artisan 时,出现以下错误:

In Builder.php line 369:
No query results for model [App\Path] /

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

标签: laravel

解决方案


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

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

推荐阅读