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

Laravel 9中SQLite测试环境下修改表结构无法新增列的问题

Laravel 9 SQLite测试环境下修改现有表结构的问题

我编写了如下迁移文件,用于修改默认的users表:

2022_07_27_151149_update_users_table.php

protected $tableName = 'users';

public function up()
{
    Schema::table($this->tableName, function (Blueprint $table) {
        $table->string('first_name', 75);
        $table->string('last_name', 75);
        $table->string('mobile', 12);
        $table->dropColumn('name');
        dump('in closure'); // <--- 此代码已执行
    });
    dump('completed up'); // <--- 此代码已执行
}

public function down()
{
    Schema::table($this->tableName, function (Blueprint $table) {
        $table->string('name');
        
        if(Schema::hasColumn($this->tableName, 'first_name')){
            $table->dropColumn('first_name'); // 若不包裹此代码会报错
        }
        if(Schema::hasColumn($this->tableName, 'last_name')){
            $table->dropColumn('last_name');
        }
        if(Schema::hasColumn($this->tableName, 'mobile')){
            $table->dropColumn('mobile');
        }
    });
}

我已更新模型工厂以适配这些修改:

public function definition()
{
    return [
        'first_name' => fake()->firstName(),
        'last_name' => fake()->lastName(),
        'mobile' => fake()->phoneNumber(),
        'email' => fake()->safeEmail(),
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
    ];
}

但执行任何测试时都会抛出异常:PDOException: SQLSTATE[HY000]: General error: 1 table users has no column named first_name

测试代码如下:

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;
    use DatabaseMigrations, RefreshDatabase;

    /**
     * @group debug
     */
    public function testDebug(): void
    {
        $user = User::factory()->create(); // <--- 错误发生在此处
        dd($user->toArray());
    }
}

如何在SQLite测试环境中通过Laravel迁移修改现有表结构?

备注:我已解决了事务相关问题


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 11:45:32