You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel迁移报错:SQLite数据库不存在及表缺失问题求助

问题描述

我花了约一小时排查问题:为重建数据库,我删除了database.sqlite文件,此前该操作已执行数十次,但本次运行php artisan migrate:fresh时出现如下错误:

Database file at path [{..}/database/database.sqlite] does not exist. Ensure this is an absolute path to the database. (Connection: sqlite, SQL: PRAGMA foreign_keys = ON;)

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:829
    825▕                     $this->getName(), $query, $this->prepareBindings($bindings), $e
    826▕                 );
    827▕             }
    828▕ 
  ➜ 829▕             throw new QueryException(
    830▕                 $this->getName(), $query, $this->prepareBindings($bindings), $e
    831▕             );
    832▕         }
    833▕     }

  1   [internal]:0
      Illuminate\Foundation\Application::Illuminate\Foundation\{closure}(Object(App\Providers\AppServiceProvider))
      +17 vendor frames 

  19  app/Providers/AppServiceProvider.php:24
      Illuminate\Support\Facades\Facade::__callStatic("table")

此前该命令会自动创建数据库,为何现在失效?

手动在原目录创建database.sqlite后,又出现新错误:

SQLSTATE[HY000]: General error: 1 no such table: kingdoms (Connection: sqlite, SQL: select count(*) as aggregate from "kingdoms")

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:829
    825▕                     $this->getName(), $query, $this->prepareBindings($bindings), $e
    826▕                 );
    827▕             }
    828▕ 
  ➜ 829▕             throw new QueryException(
    830▕                 $this->getName(), $query, $this->prepareBindings($bindings), $e
    831▕             );
    832▕         }
    833▕     }

我怀疑是create_kingdoms_table.php迁移文件的问题,删除该文件并清除缓存后,错误仍未解决。

解决方案

1. 核心问题定位

从错误堆栈能明确看到:服务提供者AppServiceProvider.php第24行的代码,在迁移执行前就提前发起了数据库查询。

当你删除database.sqlite后,migrate:fresh还没来得及创建数据库,服务提供者就先尝试连接数据库执行操作,导致“文件不存在”的错误;手动创建数据库后,迁移还未生成kingdoms表,服务提供者又去查询该表,自然触发“表不存在”的报错。

2. 具体修复步骤

  • 修改服务提供者逻辑:打开app/Providers/AppServiceProvider.php,找到第24行的数据库查询代码(比如DB::table('kingdoms')相关操作),将其包裹在条件判断中,避免在迁移命令执行时运行:
    public function boot()
    {
        // 仅在非命令行环境,或非迁移类命令时执行查询
        if (!app()->runningInConsole() || !in_array(request()->server('argv')[1] ?? '', ['migrate', 'migrate:fresh'])) {
            // 原来的数据库查询代码
            // 例:$kingdomCount = DB::table('kingdoms')->count();
            // ...
        }
    }
    
  • 恢复迁移文件:重新生成create_kingdoms_table迁移文件(如果之前删除了):
    php artisan make:migration create_kingdoms_table
    
    并在生成的文件中补全创建kingdoms表的结构逻辑。
  • 重新执行迁移:确保服务提供者修复完成后,运行命令重建数据库:
    php artisan migrate:fresh
    

3. 额外排查优化

  • 检查.env中的DB_DATABASE配置,建议使用绝对路径避免路径解析问题:
    DB_DATABASE=/你的项目绝对路径/database/database.sqlite
    
  • 清除配置缓存:
    php artisan config:clear
    

内容的提问来源于stack exchange,提问作者Dude2093350

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 15:12:56