首页 > 解决方案 > QueryException: 一般错误: 1 no such table: {table_name} (SQL: select * from "{table_name}")

问题描述

PHPUnit 上的所有测试都运行良好。但是当我添加View::share时,AppServiceProvider所有的 PHPUnit 测试都失败了。

AppServiceProvider.php

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        \View::share('categories', \App\Models\Category::all());
    }
}

错误

Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: categories (SQL: select * from "categories")

我已经RefreshDatabase在我的所有测试中使用过。

请指导我,我该如何解决这个问题。我应该在哪里调用View::shareLaravel 应用程序,所以所有测试都应该通过。

标签: phplaravellaravel-5phpunit

解决方案


发生这种情况是因为数据库甚至可能不存在,并且提供程序启动假设数据库/表已启动并正在运行。

通过包裹它来保护它

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
       if(\Schema::hasTable('categories'){
        \View::share('categories', \App\Models\Category::all());
       }
    }
}

推荐阅读