laravel - 使用在服务提供者中实例化对象的工匠没有查询结果错误
问题描述
我创建了一个提供类 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 对象?解决这个问题的唯一方法似乎是为“/”添加一个虚拟记录。
解决方案
您可以从控制台检查应用程序是否正在运行并调整其逻辑,例如:
$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;
});
推荐阅读
- excel - 使用 awk 和 bash 将 Data.txt 转换为 data.csv
- prometheus - Prometheus:是否可以在 prometheus Web UI 中创建/配置警报组?
- java - 在 Spring @Query 中使用变量
- c# - 任何人都可以对我在执行 .net 控制台应用程序时收到的错误有所了解。(System.Runtime.InteropServices.COMException (0x80040111)
- css - 在 React 中覆盖 CSS
- python - 按月计算 Python 循环时间
- cocoa - 在 Cocoa 应用中管理多个非文档窗口
- uwp - 将 MPU6050 与 Windows 10 IoT (windows.devices.sensors) 集成
- python - 芹菜工人失败任务重新排队逻辑(RabbitMQ)
- python - 寻找支持阿拉伯语的 NLP 库